id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
160,965 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
The provided code snippet includes necessary dependencies for implementing the `parse_raw_channel_mentions` function. Write a Python function `def parse_raw_channel_mentions(text: str) -> List[int]` to solve the following problem:
A helper function that parses mentions from a string as an array of :class:`~nextcord.abc.GuildChannel` IDs matched with the syntax of ``<#channel_id>``. .. versionadded:: 2.2 Parameters ---------- text: :class:`str` The text to parse mentions from. Returns ------- List[:class:`int`] A list of channel IDs that were mentioned.
Here is the function:
def parse_raw_channel_mentions(text: str) -> List[int]:
"""A helper function that parses mentions from a string as an array of :class:`~nextcord.abc.GuildChannel` IDs
matched with the syntax of ``<#channel_id>``.
.. versionadded:: 2.2
Parameters
----------
text: :class:`str`
The text to parse mentions from.
Returns
-------
List[:class:`int`]
A list of channel IDs that were mentioned.
"""
return [int(x) for x in re.findall(r"<#(\d{15,20})>", text)] | A helper function that parses mentions from a string as an array of :class:`~nextcord.abc.GuildChannel` IDs matched with the syntax of ``<#channel_id>``. .. versionadded:: 2.2 Parameters ---------- text: :class:`str` The text to parse mentions from. Returns ------- List[:class:`int`] A list of channel IDs that were mentioned. |
160,966 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
T = TypeVar("T")
def as_chunks(iterator: Iterator[T], max_size: int) -> Iterator[List[T]]:
... | null |
160,967 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
T = TypeVar("T")
def as_chunks(iterator: AsyncIterator[T], max_size: int) -> AsyncIterator[List[T]]:
... | null |
160,968 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
T = TypeVar("T")
_Iter = Union[Iterator[T], AsyncIterator[T]]
def _chunk(iterator: Iterator[T], max_size: int) -> Iterator[List[T]]:
ret = []
n = 0
for item in iterator:
ret.append(item)
n += 1
if n == max_size:
yield ret
ret = []
n = 0
if ret:
yield ret
async def _achunk(iterator: AsyncIterator[T], max_size: int) -> AsyncIterator[List[T]]:
ret = []
n = 0
async for item in iterator:
ret.append(item)
n += 1
if n == max_size:
yield ret
ret = []
n = 0
if ret:
yield ret
The provided code snippet includes necessary dependencies for implementing the `as_chunks` function. Write a Python function `def as_chunks(iterator: _Iter[T], max_size: int) -> _Iter[List[T]]` to solve the following problem:
A helper function that collects an iterator into chunks of a given size. .. versionadded:: 2.0 Parameters ---------- iterator: Union[:class:`collections.abc.Iterator`, :class:`collections.abc.AsyncIterator`] The iterator to chunk, can be sync or async. max_size: :class:`int` The maximum chunk size. .. warning:: The last chunk collected may not be as large as ``max_size``. Returns ------- Union[:class:`Iterator`, :class:`AsyncIterator`] A new iterator which yields chunks of a given size.
Here is the function:
def as_chunks(iterator: _Iter[T], max_size: int) -> _Iter[List[T]]:
"""A helper function that collects an iterator into chunks of a given size.
.. versionadded:: 2.0
Parameters
----------
iterator: Union[:class:`collections.abc.Iterator`, :class:`collections.abc.AsyncIterator`]
The iterator to chunk, can be sync or async.
max_size: :class:`int`
The maximum chunk size.
.. warning::
The last chunk collected may not be as large as ``max_size``.
Returns
-------
Union[:class:`Iterator`, :class:`AsyncIterator`]
A new iterator which yields chunks of a given size.
"""
if max_size <= 0:
raise ValueError("Chunk sizes must be greater than 0.")
if isinstance(iterator, AsyncIterator):
return _achunk(iterator, max_size)
return _chunk(iterator, max_size) | A helper function that collects an iterator into chunks of a given size. .. versionadded:: 2.0 Parameters ---------- iterator: Union[:class:`collections.abc.Iterator`, :class:`collections.abc.AsyncIterator`] The iterator to chunk, can be sync or async. max_size: :class:`int` The maximum chunk size. .. warning:: The last chunk collected may not be as large as ``max_size``. Returns ------- Union[:class:`Iterator`, :class:`AsyncIterator`] A new iterator which yields chunks of a given size. |
160,969 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
TimestampStyle = Literal["f", "F", "d", "D", "t", "T", "R"]
def format_ts(ts: int, /, style: Optional[TimestampStyle] = None) -> str:
"""A helper function to format a Unix timestamp as an :class:`int` for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown.
+-------------+----------------------------+-----------------+
| Style | Example Output | Description |
+=============+============================+=================+
| t | 22:57 | Short Time |
+-------------+----------------------------+-----------------+
| T | 22:57:58 | Long Time |
+-------------+----------------------------+-----------------+
| d | 17/05/2016 | Short Date |
+-------------+----------------------------+-----------------+
| D | 17 May 2016 | Long Date |
+-------------+----------------------------+-----------------+
| f (default) | 17 May 2016 22:57 | Short Date Time |
+-------------+----------------------------+-----------------+
| F | Tuesday, 17 May 2016 22:57 | Long Date Time |
+-------------+----------------------------+-----------------+
| R | 5 years ago | Relative Time |
+-------------+----------------------------+-----------------+
Note that the exact output depends on the user's locale setting in the client. The example output
presented is using the ``en-GB`` locale.
.. versionadded:: 2.6
Parameters
----------
ts: :class:`int`
The Unix timestamp to format.
style: :class:`str`
The style to format the timestamp with.
Returns
-------
:class:`str`
The formatted string.
"""
if not isinstance(ts, int): # pyright: ignore[reportUnnecessaryIsInstance]
raise InvalidArgument("'ts' must be of type 'int'")
if style is None:
return f"<t:{ts}>"
return f"<t:{ts}:{style}>"
class InvalidArgument(ClientException):
"""Exception that's raised when an argument to a function
is invalid some way (e.g. wrong value or wrong type).
This could be considered the analogous of ``ValueError`` and
``TypeError`` except inherited from :exc:`ClientException` and thus
:exc:`DiscordException`.
"""
The provided code snippet includes necessary dependencies for implementing the `format_dt` function. Write a Python function `def format_dt(dt: datetime.datetime, /, style: Optional[TimestampStyle] = None) -> str` to solve the following problem:
A helper function to format a :class:`datetime.datetime` for presentation within Discord. This allows for a locale-independent way of presenting data using Discord specific Markdown. +-------------+----------------------------+-----------------+ | Style | Example Output | Description | +=============+============================+=================+ | t | 22:57 | Short Time | +-------------+----------------------------+-----------------+ | T | 22:57:58 | Long Time | +-------------+----------------------------+-----------------+ | d | 17/05/2016 | Short Date | +-------------+----------------------------+-----------------+ | D | 17 May 2016 | Long Date | +-------------+----------------------------+-----------------+ | f (default) | 17 May 2016 22:57 | Short Date Time | +-------------+----------------------------+-----------------+ | F | Tuesday, 17 May 2016 22:57 | Long Date Time | +-------------+----------------------------+-----------------+ | R | 5 years ago | Relative Time | +-------------+----------------------------+-----------------+ Note that the exact output depends on the user's locale setting in the client. The example output presented is using the ``en-GB`` locale. .. versionadded:: 2.0 Parameters ---------- dt: :class:`datetime.datetime` The datetime to format. style: :class:`str` The style to format the datetime with. Returns ------- :class:`str` The formatted string.
Here is the function:
def format_dt(dt: datetime.datetime, /, style: Optional[TimestampStyle] = None) -> str:
"""A helper function to format a :class:`datetime.datetime` for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown.
+-------------+----------------------------+-----------------+
| Style | Example Output | Description |
+=============+============================+=================+
| t | 22:57 | Short Time |
+-------------+----------------------------+-----------------+
| T | 22:57:58 | Long Time |
+-------------+----------------------------+-----------------+
| d | 17/05/2016 | Short Date |
+-------------+----------------------------+-----------------+
| D | 17 May 2016 | Long Date |
+-------------+----------------------------+-----------------+
| f (default) | 17 May 2016 22:57 | Short Date Time |
+-------------+----------------------------+-----------------+
| F | Tuesday, 17 May 2016 22:57 | Long Date Time |
+-------------+----------------------------+-----------------+
| R | 5 years ago | Relative Time |
+-------------+----------------------------+-----------------+
Note that the exact output depends on the user's locale setting in the client. The example output
presented is using the ``en-GB`` locale.
.. versionadded:: 2.0
Parameters
----------
dt: :class:`datetime.datetime`
The datetime to format.
style: :class:`str`
The style to format the datetime with.
Returns
-------
:class:`str`
The formatted string.
"""
if not isinstance(dt, datetime.datetime): # pyright: ignore[reportUnnecessaryIsInstance]
raise InvalidArgument("'dt' must be of type 'datetime.datetime'")
return format_ts(int(dt.timestamp()), style=style) | A helper function to format a :class:`datetime.datetime` for presentation within Discord. This allows for a locale-independent way of presenting data using Discord specific Markdown. +-------------+----------------------------+-----------------+ | Style | Example Output | Description | +=============+============================+=================+ | t | 22:57 | Short Time | +-------------+----------------------------+-----------------+ | T | 22:57:58 | Long Time | +-------------+----------------------------+-----------------+ | d | 17/05/2016 | Short Date | +-------------+----------------------------+-----------------+ | D | 17 May 2016 | Long Date | +-------------+----------------------------+-----------------+ | f (default) | 17 May 2016 22:57 | Short Date Time | +-------------+----------------------------+-----------------+ | F | Tuesday, 17 May 2016 22:57 | Long Date Time | +-------------+----------------------------+-----------------+ | R | 5 years ago | Relative Time | +-------------+----------------------------+-----------------+ Note that the exact output depends on the user's locale setting in the client. The example output presented is using the ``en-GB`` locale. .. versionadded:: 2.0 Parameters ---------- dt: :class:`datetime.datetime` The datetime to format. style: :class:`str` The style to format the datetime with. Returns ------- :class:`str` The formatted string. |
160,970 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
MISSING: Any = _MissingSentinel()
_FUNCTION_DESCRIPTION_REGEX = re.compile(r"\A(?:.|\n)+?(?=\Z|\r?\n\r?\n)", re.MULTILINE)
_GOOGLE_DOCSTRING_ARG_REGEX = re.compile(
rf"^{_ARG_NAME_SUBREGEX}[ \t]*(?:\({_ARG_TYPE_SUBREGEX}\))?[ \t]*:[ \t]*{_ARG_DESCRIPTION_SUBREGEX}",
re.MULTILINE,
)
_SPHINX_DOCSTRING_ARG_REGEX = re.compile(
rf"^:param {_ARG_NAME_SUBREGEX}:[ \t]+{_ARG_DESCRIPTION_SUBREGEX}[ \t]*(?::type [^\s:]+:[ \t]+{_ARG_TYPE_SUBREGEX})?",
re.MULTILINE,
)
_NUMPY_DOCSTRING_ARG_REGEX = re.compile(
rf"^{_ARG_NAME_SUBREGEX}(?:[ \t]*:)?(?:[ \t]+{_ARG_TYPE_SUBREGEX})?[ \t]*\r?\n[ \t]+{_ARG_DESCRIPTION_SUBREGEX}",
re.MULTILINE,
)
def _trim_text(text: str, max_chars: int) -> str:
"""Trims a string and adds an ellpsis if it exceeds the maximum length.
Parameters
----------
text: :class:`str`
The string to trim.
max_chars: :class:`int`
The maximum number of characters to allow.
Returns
-------
:class:`str`
The trimmed string.
"""
if len(text) > max_chars:
# \u2026 = ellipsis
return text[: max_chars - 1] + "\u2026"
return text
The provided code snippet includes necessary dependencies for implementing the `parse_docstring` function. Write a Python function `def parse_docstring(func: Callable[..., Any], max_chars: int = MISSING) -> Dict[str, Any]` to solve the following problem:
Parses the docstring of a function into a dictionary. Parameters ---------- func: :data:`~typing.Callable` The function to parse the docstring of. max_chars: :class:`int` The maximum number of characters to allow in the descriptions. If MISSING, then there is no maximum. Returns ------- :class:`Dict[str, Any]` The parsed docstring including the function description and descriptions of arguments.
Here is the function:
def parse_docstring(func: Callable[..., Any], max_chars: int = MISSING) -> Dict[str, Any]:
"""Parses the docstring of a function into a dictionary.
Parameters
----------
func: :data:`~typing.Callable`
The function to parse the docstring of.
max_chars: :class:`int`
The maximum number of characters to allow in the descriptions.
If MISSING, then there is no maximum.
Returns
-------
:class:`Dict[str, Any]`
The parsed docstring including the function description and
descriptions of arguments.
"""
description = ""
args = {}
if docstring := inspect.cleandoc(inspect.getdoc(func) or "").strip():
# Extract the function description
description_match = _FUNCTION_DESCRIPTION_REGEX.search(docstring)
if description_match:
description = re.sub(r"\n\s*", " ", description_match.group(0)).strip()
if max_chars is not MISSING:
description = _trim_text(description, max_chars)
# Extract the arguments
# For Google-style, look only at the lines that are indented
section_lines = inspect.cleandoc(
"\n".join(line for line in docstring.splitlines() if line.startswith(("\t", " ")))
)
docstring_styles = [
_GOOGLE_DOCSTRING_ARG_REGEX.finditer(section_lines),
_SPHINX_DOCSTRING_ARG_REGEX.finditer(docstring),
_NUMPY_DOCSTRING_ARG_REGEX.finditer(docstring),
]
# choose the style with the largest number of arguments matched
matched_args = []
actual_args = inspect.signature(func).parameters.keys()
for matches in docstring_styles:
style_matched_args = [match for match in matches if match.group("name") in actual_args]
if len(style_matched_args) > len(matched_args):
matched_args = style_matched_args
for arg in matched_args:
arg_description = re.sub(r"\n\s*", " ", arg.group("description")).strip()
if max_chars is not MISSING:
arg_description = _trim_text(arg_description, max_chars)
args[arg.group("name")] = arg_description
return {"description": description, "args": args} | Parses the docstring of a function into a dictionary. Parameters ---------- func: :data:`~typing.Callable` The function to parse the docstring of. max_chars: :class:`int` The maximum number of characters to allow in the descriptions. If MISSING, then there is no maximum. Returns ------- :class:`Dict[str, Any]` The parsed docstring including the function description and descriptions of arguments. |
160,971 | from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar, List, Literal, Optional, Tuple, TypeVar, Union, cast
from .enums import ButtonStyle, ComponentType, TextInputStyle, try_enum
from .partial_emoji import PartialEmoji, _EmojiTag
from .utils import MISSING, get_slots
class Component:
"""Represents a Discord Bot UI Kit Component.
Currently, the only components supported by Discord are:
- :class:`ActionRow`
- :class:`Button`
- :class:`SelectMenu`
- :class:`TextInput`
- :class:`UserSelectMenu`
- :class:`ChannelSelectMenu`
- :class:`RoleSelectMenu`
- :class:`MentionableSelectMenu`
This class is abstract and cannot be instantiated.
.. versionadded:: 2.0
Attributes
----------
type: :class:`ComponentType`
The type of component.
"""
__slots__: Tuple[str, ...] = ()
__repr_info__: ClassVar[Tuple[str, ...]]
type: ComponentType
def __repr__(self) -> str:
attrs = " ".join(f"{key}={getattr(self, key)!r}" for key in self.__repr_info__)
return f"<{self.__class__.__name__} {attrs}>"
def _raw_construct(cls, **kwargs) -> Self:
self = cls.__new__(cls)
for slot in get_slots(cls):
try:
value = kwargs[slot]
except KeyError:
pass
else:
setattr(self, slot, value)
return self
def to_dict(self) -> ComponentPayload:
raise NotImplementedError
class ActionRow(Component):
"""Represents a Discord Bot UI Kit Action Row.
This is a component that holds up to 5 children components in a row.
This inherits from :class:`Component`.
.. versionadded:: 2.0
Attributes
----------
type: :class:`ComponentType`
The type of component.
children: List[:class:`Component`]
The children components that this holds, if any.
"""
__slots__: Tuple[str, ...] = ("type", "children")
__repr_info__: ClassVar[Tuple[str, ...]] = __slots__
def __init__(self, data: ComponentPayload) -> None:
self.type: ComponentType = try_enum(ComponentType, data["type"])
self.children: List[Component] = [_component_factory(d) for d in data.get("components", [])]
def to_dict(self) -> ActionRowPayload:
return {
"type": cast(Literal[1], int(self.type)),
"components": [child.to_dict() for child in self.children],
}
class Button(Component):
"""Represents a button from the Discord Bot UI Kit.
This inherits from :class:`Component`.
.. note::
The user constructible and usable type to create a button is :class:`nextcord.ui.Button`
not this one.
.. versionadded:: 2.0
Attributes
----------
style: :class:`.ButtonStyle`
The style of the button.
custom_id: Optional[:class:`str`]
The ID of the button that gets received during an interaction.
If this button is for a URL, it does not have a custom ID.
url: Optional[:class:`str`]
The URL this button sends you to.
disabled: :class:`bool`
Whether the button is disabled or not.
label: Optional[:class:`str`]
The label of the button, if any.
emoji: Optional[:class:`PartialEmoji`]
The emoji of the button, if available.
"""
__slots__: Tuple[str, ...] = (
"type",
"style",
"custom_id",
"url",
"disabled",
"label",
"emoji",
)
__repr_info__: ClassVar[Tuple[str, ...]] = __slots__
def __init__(self, data: ButtonComponentPayload) -> None:
self.type: ComponentType = try_enum(ComponentType, data["type"])
self.style: ButtonStyle = try_enum(ButtonStyle, data["style"])
self.custom_id: Optional[str] = data.get("custom_id")
self.url: Optional[str] = data.get("url")
self.disabled: bool = data.get("disabled", False)
self.label: Optional[str] = data.get("label")
self.emoji: Optional[PartialEmoji]
try:
self.emoji = PartialEmoji.from_dict(data["emoji"])
except KeyError:
self.emoji = None
def to_dict(self) -> ButtonComponentPayload:
payload = {
"type": 2,
"style": int(self.style),
"label": self.label,
"disabled": self.disabled,
}
if self.custom_id:
payload["custom_id"] = self.custom_id
if self.url:
payload["url"] = self.url
if self.emoji:
payload["emoji"] = self.emoji.to_dict()
return payload # type: ignore
SelectMenu = StringSelectMenu
class TextInput(Component):
__slots__: Tuple[str, ...] = (
"type",
"style",
"custom_id",
"label",
"min_length",
"max_length",
"required",
"value",
"placeholder",
)
__repr_info__: ClassVar[Tuple[str, ...]] = __slots__
def __init__(self, data: TextInputComponentPayload) -> None:
self.type: ComponentType = try_enum(ComponentType, data["type"])
self.style: TextInputStyle = try_enum(
TextInputStyle,
data.get("style", 1),
)
self.custom_id: str = data.get("custom_id")
self.label: str = data.get("label")
self.min_length: Optional[int] = data.get("min_length")
self.max_length: Optional[int] = data.get("max_length")
self.required: Optional[bool] = data.get("required")
self.value: Optional[str] = data.get("value")
self.placeholder: Optional[str] = data.get("placeholder")
def to_dict(self) -> TextInputComponentPayload:
payload = {
"type": 4,
"custom_id": self.custom_id,
"style": int(self.style.value),
"label": self.label,
}
if self.min_length:
payload["min_length"] = self.min_length
if self.max_length:
payload["max_length"] = self.max_length
if self.required is not None:
payload["required"] = self.required
if self.value:
payload["value"] = self.value
if self.placeholder:
payload["placeholder"] = self.placeholder
return payload # type: ignore
class ComponentType(IntEnum):
"""Represents the component type of a component.
.. versionadded:: 2.0
"""
action_row = 1
"""Represents the group component which holds different components in a row."""
button = 2
"""Represents a button component."""
select = 3
"""Represents a select string component."""
string_select = 3
"""An alias for :attr:`ComponentType.select`.
.. versionadded:: 2.3
"""
text_input = 4
"""Represents a text input component."""
user_select = 5
"""Represents a user select component.
.. versionadded:: 2.3
"""
role_select = 6
"""Represents a role select component.
.. versionadded:: 2.3
"""
mentionable_select = 7
"""Represents a mentionable select component.
.. versionadded:: 2.3
"""
channel_select = 8
"""Represents a channel select component.
.. versionadded:: 2.3
"""
def try_enum(cls: Type[T], val: Any) -> T:
"""A function that tries to turn the value into enum ``cls``.
If it fails it returns a proxy invalid value instead.
"""
try:
return cls(val)
except ValueError:
return UnknownEnumValue(name=f"unknown_{val}", value=val) # type: ignore
class ActionRow(TypedDict):
type: Literal[1]
components: List[Component]
def _component_factory(data: ComponentPayload) -> Component:
component_type = data["type"]
if component_type == 1:
return ActionRow(data)
if component_type == 2:
return Button(data) # type: ignore
if component_type == 3:
return SelectMenu(data) # type: ignore
if component_type == 4:
return TextInput(data) # type: ignore
as_enum = try_enum(ComponentType, component_type)
return Component._raw_construct(type=as_enum) | null |
160,972 | from __future__ import annotations
import asyncio
import logging
import os
import sys
import time
import traceback
from functools import partial
from itertools import groupby
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Iterator,
List,
Optional,
Set,
Tuple,
)
from typing_extensions import Self
from ..components import (
ActionRow as ActionRowComponent,
Button as ButtonComponent,
Component,
SelectMenu as SelectComponent,
TextInput as TextComponent,
_component_factory,
)
from .item import Item, ItemCallbackType
def _walk_all_components(components: List[Component]) -> Iterator[Component]:
for item in components:
if isinstance(item, ActionRowComponent):
yield from item.children
else:
yield item | null |
160,973 | from __future__ import annotations
import asyncio
import logging
import os
import sys
import time
import traceback
from functools import partial
from itertools import groupby
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Iterator,
List,
Optional,
Set,
Tuple,
)
from typing_extensions import Self
from ..components import (
ActionRow as ActionRowComponent,
Button as ButtonComponent,
Component,
SelectMenu as SelectComponent,
TextInput as TextComponent,
_component_factory,
)
from .item import Item, ItemCallbackType
class Item(Generic[V_co]):
def __init__(self) -> None:
def to_component_dict(self) -> ComponentPayload:
def refresh_component(self, component: Component) -> None:
def refresh_state(
self, data: ComponentInteractionData, state: ConnectionState, guild: Optional[Guild]
) -> None:
def from_component(cls, component: Component) -> Self:
def type(self) -> ComponentType:
def is_dispatchable(self) -> bool:
def is_persistent(self) -> bool:
def __repr__(self) -> str:
def row(self) -> Optional[int]:
def row(self, value: Optional[int]) -> None:
def width(self) -> int:
def view(self) -> Optional[V_co]:
async def callback(self, interaction: Interaction) -> None:
class Button(Item[V_co]):
def __init__(
self,
*,
style: ButtonStyle = ButtonStyle.secondary,
label: Optional[str] = None,
disabled: bool = False,
custom_id: Optional[str] = None,
url: Optional[str] = None,
emoji: Optional[Union[str, Emoji, PartialEmoji]] = None,
row: Optional[int] = None,
) -> None:
def style(self) -> ButtonStyle:
def style(self, value: ButtonStyle) -> None:
def custom_id(self) -> Optional[str]:
def custom_id(self, value: Optional[str]) -> None:
def url(self) -> Optional[str]:
def url(self, value: Optional[str]) -> None:
def disabled(self) -> bool:
def disabled(self, value: bool) -> None:
def label(self) -> Optional[str]:
def label(self, value: Optional[str]) -> None:
def emoji(self) -> Optional[PartialEmoji]:
def emoji(self, value: Optional[Union[str, Emoji, PartialEmoji]]) -> None:
def from_component(cls, button: ButtonComponent) -> Self:
def type(self) -> ComponentType:
def to_component_dict(self) -> ButtonComponentPayload:
def is_dispatchable(self) -> bool:
def is_persistent(self) -> bool:
def refresh_component(self, button: ButtonComponent) -> None:
class TextInput(Item[V_co]):
def __init__(
self,
label: str,
*,
style: TextInputStyle = TextInputStyle.short,
custom_id: str = MISSING,
row: Optional[int] = None,
min_length: Optional[int] = 0,
max_length: Optional[int] = 4000,
required: Optional[bool] = None,
default_value: Optional[str] = None,
placeholder: Optional[str] = None,
) -> None:
def style(self) -> TextInputStyle:
def style(self, value: TextInputStyle) -> None:
def custom_id(self) -> Optional[str]:
def custom_id(self, value: Optional[str]) -> None:
def label(self) -> str:
def label(self, value: str) -> None:
def min_length(self) -> Optional[int]:
def min_length(self, value: int) -> None:
def max_length(self) -> Optional[int]:
def max_length(self, value: int) -> None:
def required(self) -> Optional[bool]:
def required(self, value: Optional[bool]) -> None:
def default_value(self) -> Optional[str]:
def default_value(self, value: Optional[str]) -> None:
def value(self) -> Optional[str]:
def placeholder(self) -> Optional[str]:
def placeholder(self, value: Optional[str]) -> None:
def width(self) -> int:
def from_component(cls, text_input: TextInputComponent) -> Self:
def type(self) -> ComponentType:
def to_component_dict(self) -> TextInputComponentPayload:
def is_dispatchable(self) -> bool:
def refresh_component(self, text_input: TextInputComponent) -> None:
def refresh_state(
self, data: ComponentInteractionData, state: ConnectionState, guild: Optional[Guild]
) -> None:
def _component_to_item(component: Component) -> Item:
if isinstance(component, ButtonComponent):
from .button import Button
return Button.from_component(component)
if isinstance(component, SelectComponent):
from .select import Select
return Select.from_component(component)
if isinstance(component, TextComponent):
from .text_input import TextInput
return TextInput.from_component(component)
return Item.from_component(component) | null |
160,974 | from __future__ import annotations
import asyncio
import os
import sys
import time
import traceback
from functools import partial
from itertools import groupby
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Optional, Set, Tuple
from ..components import Component
from ..utils import MISSING
from .item import Item
from .view import _component_to_item, _ViewWeights, _walk_all_components
class ComponentInteractionData(TypedDict):
custom_id: str
component_type: ComponentType
values: NotRequired[List[str]]
value: NotRequired[str]
resolved: NotRequired[ComponentInteractionResolved]
ModalSubmitComponentInteractionData = Union[
ModalSubmitActionRowInteractionData,
ComponentInteractionData,
]
def _walk_component_interaction_data(
components: List[ModalSubmitComponentInteractionData],
) -> Iterator[ComponentInteractionData]:
for item in components:
if "components" in item:
yield from item["components"] # type: ignore
else:
yield item | null |
160,975 | from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Callable, Generic, List, Optional, Tuple, TypeVar
from ...components import RoleSelectMenu
from ...enums import ComponentType
from ...interactions import ClientT
from ...role import Role
from ...state import ConnectionState
from ...utils import MISSING
from ..item import ItemCallbackType
from ..view import View
from .base import SelectBase, SelectValuesBase
V_co = TypeVar("V_co", bound="View", covariant=True)
class RoleSelect(SelectBase, Generic[V_co]):
"""Represents a UI role select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen,
use :attr:`RoleSelect.values`.
.. versionadded:: 2.3
Parameters
------------
custom_id: :class:`str`
The ID of the select menu that gets received during an interaction.
If not given then one is generated for you.
placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any.
min_values: :class:`int`
The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
max_values: :class:`int`
The maximum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
disabled: :class:`bool`
Whether the select is disabled or not. Defaults to ``False``.
row: Optional[:class:`int`]
The relative row this select menu belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd
like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed).
"""
__item_repr_attributes__: Tuple[str, ...] = (
"placeholder",
"min_values",
"max_values",
"disabled",
)
def __init__(
self,
*,
custom_id: str = MISSING,
placeholder: Optional[str] = None,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False,
row: Optional[int] = None,
) -> None:
super().__init__(
custom_id=custom_id,
min_values=min_values,
max_values=max_values,
disabled=disabled,
row=row,
placeholder=placeholder,
)
self._selected_values: RoleSelectValues = RoleSelectValues()
self._underlying = RoleSelectMenu._raw_construct(
custom_id=self.custom_id,
type=ComponentType.role_select,
placeholder=self.placeholder,
min_values=self.min_values,
max_values=self.max_values,
disabled=self.disabled,
)
def values(self) -> RoleSelectValues:
""":class:`.ui.RoleSelectValues`: A list of :class:`.Role` that have been selected by the user."""
return self._selected_values
def to_component_dict(self) -> RoleSelectMenuPayload:
return self._underlying.to_dict()
def from_component(cls, component: RoleSelectMenu) -> Self:
return cls(
custom_id=component.custom_id,
placeholder=component.placeholder,
min_values=component.min_values,
max_values=component.max_values,
disabled=component.disabled,
row=None,
)
def refresh_state(
self, data: ComponentInteractionData, state: ConnectionState, guild: Optional[Guild]
) -> None:
self._selected_values = RoleSelectValues.construct(
data.get("values", []),
data.get("resolved", {}),
state,
guild,
)
ClientT = TypeVar("ClientT", bound="Client")
MISSING: Any = _MissingSentinel()
ItemCallbackType = Callable[[Any, I, Interaction[ClientT]], Coroutine[Any, Any, Any]]
The provided code snippet includes necessary dependencies for implementing the `role_select` function. Write a Python function `def role_select( *, placeholder: Optional[str] = None, custom_id: str = MISSING, min_values: int = 1, max_values: int = 1, disabled: bool = False, row: Optional[int] = None, ) -> Callable[ [ItemCallbackType[RoleSelect[V_co], ClientT]], ItemCallbackType[RoleSelect[V_co], ClientT] ]` to solve the following problem:
A decorator that attaches a role select menu to a component. The function being decorated should have three parameters, ``self`` representing the :class:`.ui.View`, the :class:`.ui.RoleSelect` being pressed and the :class:`.Interaction` you receive. In order to get the selected items that the user has chosen within the callback use :attr:`RoleSelect.values`. .. versionadded:: 2.3 Parameters ---------- placeholder: Optional[:class:`str`] The placeholder text that is shown if nothing is selected, if any. custom_id: :class:`str` The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts. row: Optional[:class:`int`] The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed). min_values: :class:`int` The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. max_values: :class:`int` The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. disabled: :class:`bool` Whether the select is disabled or not. Defaults to ``False``.
Here is the function:
def role_select(
*,
placeholder: Optional[str] = None,
custom_id: str = MISSING,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False,
row: Optional[int] = None,
) -> Callable[
[ItemCallbackType[RoleSelect[V_co], ClientT]], ItemCallbackType[RoleSelect[V_co], ClientT]
]:
"""A decorator that attaches a role select menu to a component.
The function being decorated should have three parameters, ``self`` representing
the :class:`.ui.View`, the :class:`.ui.RoleSelect` being pressed and
the :class:`.Interaction` you receive.
In order to get the selected items that the user has chosen within the callback
use :attr:`RoleSelect.values`.
.. versionadded:: 2.3
Parameters
----------
placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any.
custom_id: :class:`str`
The ID of the select menu that gets received during an interaction.
It is recommended not to set this parameter to prevent conflicts.
row: Optional[:class:`int`]
The relative row this select menu belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd
like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed).
min_values: :class:`int`
The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
max_values: :class:`int`
The maximum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
disabled: :class:`bool`
Whether the select is disabled or not. Defaults to ``False``.
"""
def decorator(func: ItemCallbackType) -> ItemCallbackType:
if not asyncio.iscoroutinefunction(func):
raise TypeError("Select function must be a coroutine function")
func.__discord_ui_model_type__ = RoleSelect
func.__discord_ui_model_kwargs__ = {
"placeholder": placeholder,
"custom_id": custom_id,
"row": row,
"min_values": min_values,
"max_values": max_values,
"disabled": disabled,
}
return func
return decorator | A decorator that attaches a role select menu to a component. The function being decorated should have three parameters, ``self`` representing the :class:`.ui.View`, the :class:`.ui.RoleSelect` being pressed and the :class:`.Interaction` you receive. In order to get the selected items that the user has chosen within the callback use :attr:`RoleSelect.values`. .. versionadded:: 2.3 Parameters ---------- placeholder: Optional[:class:`str`] The placeholder text that is shown if nothing is selected, if any. custom_id: :class:`str` The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts. row: Optional[:class:`int`] The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed). min_values: :class:`int` The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. max_values: :class:`int` The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. disabled: :class:`bool` Whether the select is disabled or not. Defaults to ``False``. |
160,976 | from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Callable, Generic, List, Optional, Tuple, TypeVar
from ...components import MentionableSelectMenu
from ...enums import ComponentType
from ...interactions import ClientT
from ...member import Member
from ...role import Role
from ...user import User
from ...utils import MISSING
from ..item import ItemCallbackType
from ..view import View
from .base import SelectBase, SelectValuesBase
V_co = TypeVar("V_co", bound="View", covariant=True)
class MentionableSelect(SelectBase, Generic[V_co]):
"""Represents a UI mentionable select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen,
use :attr:`MentionableSelect.values`.
.. versionadded:: 2.3
Parameters
------------
custom_id: :class:`str`
The ID of the select menu that gets received during an interaction.
If not given then one is generated for you.
placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any.
min_values: :class:`int`
The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
max_values: :class:`int`
The maximum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
disabled: :class:`bool`
Whether the select is disabled or not. Defaults to ``False``.
row: Optional[:class:`int`]
The relative row this select menu belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd
like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed).
"""
__item_repr_attributes__: Tuple[str, ...] = (
"placeholder",
"min_values",
"max_values",
"disabled",
)
def __init__(
self,
*,
custom_id: str = MISSING,
placeholder: Optional[str] = None,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False,
row: Optional[int] = None,
) -> None:
super().__init__(
custom_id=custom_id,
min_values=min_values,
max_values=max_values,
disabled=disabled,
row=row,
placeholder=placeholder,
)
self._selected_values: MentionableSelectValues = MentionableSelectValues()
self._underlying = MentionableSelectMenu._raw_construct(
custom_id=self.custom_id,
type=ComponentType.mentionable_select,
placeholder=self.placeholder,
min_values=self.min_values,
max_values=self.max_values,
disabled=self.disabled,
)
def values(self) -> MentionableSelectValues:
""":class:`.ui.MentionableSelectValues`: A list of Union[:class:`.Member`, :class:`nextcord.User`, :class:`.Role`] that have been selected by the user."""
return self._selected_values
def to_component_dict(self) -> MentionableSelectMenuPayload:
return self._underlying.to_dict()
def from_component(cls, component: MentionableSelectMenu) -> Self:
return cls(
custom_id=component.custom_id,
placeholder=component.placeholder,
min_values=component.min_values,
max_values=component.max_values,
disabled=component.disabled,
row=None,
)
def refresh_state(
self, data: ComponentInteractionData, state: ConnectionState, guild: Optional[Guild]
) -> None:
self._selected_values = MentionableSelectValues.construct(
data.get("values", []),
data.get("resolved", {}),
state,
guild,
)
ClientT = TypeVar("ClientT", bound="Client")
MISSING: Any = _MissingSentinel()
ItemCallbackType = Callable[[Any, I, Interaction[ClientT]], Coroutine[Any, Any, Any]]
The provided code snippet includes necessary dependencies for implementing the `mentionable_select` function. Write a Python function `def mentionable_select( *, placeholder: Optional[str] = None, custom_id: str = MISSING, min_values: int = 1, max_values: int = 1, disabled: bool = False, row: Optional[int] = None, ) -> Callable[ [ItemCallbackType[MentionableSelect[V_co], ClientT]], ItemCallbackType[MentionableSelect[V_co], ClientT], ]` to solve the following problem:
A decorator that attaches a mentionable select menu to a component. The function being decorated should have three parameters, ``self`` representing the :class:`.ui.View`, the :class:`.ui.MentionableSelect` being pressed and the :class:`.Interaction` you receive. In order to get the selected items that the user has chosen within the callback use :attr:`MentionableSelect.values`. .. versionadded:: 2.3 Parameters ------------ placeholder: Optional[:class:`str`] The placeholder text that is shown if nothing is selected, if any. custom_id: :class:`str` The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts. row: Optional[:class:`int`] The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed). min_values: :class:`int` The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. max_values: :class:`int` The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. disabled: :class:`bool` Whether the select is disabled or not. Defaults to ``False``.
Here is the function:
def mentionable_select(
*,
placeholder: Optional[str] = None,
custom_id: str = MISSING,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False,
row: Optional[int] = None,
) -> Callable[
[ItemCallbackType[MentionableSelect[V_co], ClientT]],
ItemCallbackType[MentionableSelect[V_co], ClientT],
]:
"""A decorator that attaches a mentionable select menu to a component.
The function being decorated should have three parameters, ``self`` representing
the :class:`.ui.View`, the :class:`.ui.MentionableSelect` being pressed and
the :class:`.Interaction` you receive.
In order to get the selected items that the user has chosen within the callback
use :attr:`MentionableSelect.values`.
.. versionadded:: 2.3
Parameters
------------
placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any.
custom_id: :class:`str`
The ID of the select menu that gets received during an interaction.
It is recommended not to set this parameter to prevent conflicts.
row: Optional[:class:`int`]
The relative row this select menu belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd
like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed).
min_values: :class:`int`
The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
max_values: :class:`int`
The maximum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
disabled: :class:`bool`
Whether the select is disabled or not. Defaults to ``False``.
"""
def decorator(func: ItemCallbackType) -> ItemCallbackType:
if not asyncio.iscoroutinefunction(func):
raise TypeError("Select function must be a coroutine function")
func.__discord_ui_model_type__ = MentionableSelect
func.__discord_ui_model_kwargs__ = {
"placeholder": placeholder,
"custom_id": custom_id,
"row": row,
"min_values": min_values,
"max_values": max_values,
"disabled": disabled,
}
return func
return decorator | A decorator that attaches a mentionable select menu to a component. The function being decorated should have three parameters, ``self`` representing the :class:`.ui.View`, the :class:`.ui.MentionableSelect` being pressed and the :class:`.Interaction` you receive. In order to get the selected items that the user has chosen within the callback use :attr:`MentionableSelect.values`. .. versionadded:: 2.3 Parameters ------------ placeholder: Optional[:class:`str`] The placeholder text that is shown if nothing is selected, if any. custom_id: :class:`str` The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts. row: Optional[:class:`int`] The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed). min_values: :class:`int` The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. max_values: :class:`int` The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. disabled: :class:`bool` Whether the select is disabled or not. Defaults to ``False``. |
160,977 | from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Callable, Generic, List, Optional, Tuple, TypeVar
from ...components import UserSelectMenu
from ...enums import ComponentType
from ...interactions import ClientT
from ...member import Member
from ...user import User
from ...utils import MISSING
from ..item import ItemCallbackType
from ..view import View
from .base import SelectBase, SelectValuesBase
V_co = TypeVar("V_co", bound="View", covariant=True)
class UserSelect(SelectBase, Generic[V_co]):
"""Represents a UI user select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use :attr:`UserSelect.values`.
.. versionadded:: 2.3
Parameters
----------
custom_id: :class:`str`
The ID of the select menu that gets received during an interaction.
If not given then one is generated for you.
placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any.
min_values: :class:`int`
The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
max_values: :class:`int`
The maximum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
disabled: :class:`bool`
Whether the select is disabled or not. Defaults to ``False``.
row: Optional[:class:`int`]
The relative row this select menu belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd
like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed).
"""
__item_repr_attributes__: Tuple[str, ...] = (
"placeholder",
"min_values",
"max_values",
"disabled",
)
def __init__(
self,
*,
custom_id: str = MISSING,
placeholder: Optional[str] = None,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False,
row: Optional[int] = None,
) -> None:
super().__init__(
custom_id=custom_id,
row=row,
placeholder=placeholder,
min_values=min_values,
max_values=max_values,
disabled=disabled,
)
self._selected_values: UserSelectValues = UserSelectValues()
self._underlying = UserSelectMenu._raw_construct(
custom_id=self.custom_id,
type=ComponentType.user_select,
placeholder=self.placeholder,
min_values=self.min_values,
max_values=self.max_values,
disabled=self.disabled,
)
def values(self) -> UserSelectValues:
""":class:`.ui.UserSelectValues`: A list of Union[:class:`.Member`, :class:`nextcord.User`] that have been selected by the user."""
return self._selected_values
def to_component_dict(self) -> UserSelectMenuPayload:
return self._underlying.to_dict()
def from_component(cls, component: UserSelectMenu) -> Self:
return cls(
custom_id=component.custom_id,
placeholder=component.placeholder,
min_values=component.min_values,
max_values=component.max_values,
disabled=component.disabled,
row=None,
)
def refresh_state(
self, data: ComponentInteractionData, state: ConnectionState, guild: Optional[Guild]
) -> None:
self._selected_values = UserSelectValues.construct(
data.get("values", []),
data.get("resolved", {}),
state,
guild,
)
ClientT = TypeVar("ClientT", bound="Client")
MISSING: Any = _MissingSentinel()
ItemCallbackType = Callable[[Any, I, Interaction[ClientT]], Coroutine[Any, Any, Any]]
The provided code snippet includes necessary dependencies for implementing the `user_select` function. Write a Python function `def user_select( *, placeholder: Optional[str] = None, custom_id: str = MISSING, min_values: int = 1, max_values: int = 1, disabled: bool = False, row: Optional[int] = None, ) -> Callable[ [ItemCallbackType[UserSelect[V_co], ClientT]], ItemCallbackType[UserSelect[V_co], ClientT] ]` to solve the following problem:
A decorator that attaches a user select menu to a component. The function being decorated should have three parameters, ``self`` representing the :class:`.ui.View`, the :class:`.ui.UserSelect` being pressed and the :class:`.Interaction` you receive. In order to get the selected items that the user has chosen within the callback use :attr:`UserSelect.values`. .. versionadded:: 2.3 Parameters ---------- placeholder: Optional[:class:`str`] The placeholder text that is shown if nothing is selected, if any. custom_id: :class:`str` The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts. row: Optional[:class:`int`] The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed). min_values: :class:`int` The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. max_values: :class:`int` The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. disabled: :class:`bool` Whether the select is disabled or not. Defaults to ``False``.
Here is the function:
def user_select(
*,
placeholder: Optional[str] = None,
custom_id: str = MISSING,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False,
row: Optional[int] = None,
) -> Callable[
[ItemCallbackType[UserSelect[V_co], ClientT]], ItemCallbackType[UserSelect[V_co], ClientT]
]:
"""A decorator that attaches a user select menu to a component.
The function being decorated should have three parameters, ``self`` representing
the :class:`.ui.View`, the :class:`.ui.UserSelect` being pressed and
the :class:`.Interaction` you receive.
In order to get the selected items that the user has chosen within the callback
use :attr:`UserSelect.values`.
.. versionadded:: 2.3
Parameters
----------
placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any.
custom_id: :class:`str`
The ID of the select menu that gets received during an interaction.
It is recommended not to set this parameter to prevent conflicts.
row: Optional[:class:`int`]
The relative row this select menu belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd
like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed).
min_values: :class:`int`
The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
max_values: :class:`int`
The maximum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
disabled: :class:`bool`
Whether the select is disabled or not. Defaults to ``False``.
"""
def decorator(func: ItemCallbackType) -> ItemCallbackType:
if not asyncio.iscoroutinefunction(func):
raise TypeError("Select function must be a coroutine function")
func.__discord_ui_model_type__ = UserSelect
func.__discord_ui_model_kwargs__ = {
"placeholder": placeholder,
"custom_id": custom_id,
"row": row,
"min_values": min_values,
"max_values": max_values,
"disabled": disabled,
}
return func
return decorator | A decorator that attaches a user select menu to a component. The function being decorated should have three parameters, ``self`` representing the :class:`.ui.View`, the :class:`.ui.UserSelect` being pressed and the :class:`.Interaction` you receive. In order to get the selected items that the user has chosen within the callback use :attr:`UserSelect.values`. .. versionadded:: 2.3 Parameters ---------- placeholder: Optional[:class:`str`] The placeholder text that is shown if nothing is selected, if any. custom_id: :class:`str` The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts. row: Optional[:class:`int`] The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed). min_values: :class:`int` The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. max_values: :class:`int` The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. disabled: :class:`bool` Whether the select is disabled or not. Defaults to ``False``. |
160,978 | from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Callable, Generic, List, Optional, Tuple, TypeVar
from ...abc import GuildChannel
from ...components import ChannelSelectMenu
from ...enums import ComponentType
from ...interactions import ClientT
from ...utils import MISSING
from ..item import ItemCallbackType
from ..view import View
from .base import SelectBase, SelectValuesBase
V_co = TypeVar("V_co", bound="View", covariant=True)
class ChannelSelect(SelectBase, Generic[V_co]):
"""Represents a UI channel select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen,
use :attr:`ChannelSelect.values`.
.. versionadded:: 2.3
Parameters
----------
custom_id: :class:`str`
The ID of the select menu that gets received during an interaction.
If not given then one is generated for you.
placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any.
min_values: :class:`int`
The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
max_values: :class:`int`
The maximum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
disabled: :class:`bool`
Whether the select is disabled or not. Defaults to ``False``.
row: Optional[:class:`int`]
The relative row this select menu belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd
like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed).
channel_types: List[:class:`.ChannelType`]
The types of channels that can be selected. If not given, all channel types are allowed.
"""
__item_repr_attributes__: Tuple[str, ...] = (
"placeholder",
"min_values",
"max_values",
"disabled",
"channel_types",
)
def __init__(
self,
*,
custom_id: str = MISSING,
placeholder: Optional[str] = None,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False,
row: Optional[int] = None,
channel_types: List[ChannelType] = MISSING,
) -> None:
super().__init__(
custom_id=custom_id,
placeholder=placeholder,
min_values=min_values,
max_values=max_values,
disabled=disabled,
row=row,
)
self._selected_values: ChannelSelectValues = ChannelSelectValues()
self.channel_types: List[ChannelType] = channel_types
self._underlying = ChannelSelectMenu._raw_construct(
custom_id=self.custom_id,
type=ComponentType.channel_select,
placeholder=self.placeholder,
min_values=self.min_values,
max_values=self.max_values,
disabled=self.disabled,
channel_types=channel_types,
)
def values(self) -> ChannelSelectValues:
""":class:`.ui.ChannelSelectValues`: A list of resolved :class:`.abc.GuildChannel` that have been selected by the user."""
return self._selected_values
def to_component_dict(self) -> ChannelSelectMenuPayload:
return self._underlying.to_dict()
def from_component(cls, component: ChannelSelectMenu) -> Self:
return cls(
custom_id=component.custom_id,
placeholder=component.placeholder,
min_values=component.min_values,
max_values=component.max_values,
disabled=component.disabled,
row=None,
)
def refresh_state(
self, data: ComponentInteractionData, state: ConnectionState, guild: Optional[Guild]
) -> None:
self._selected_values = ChannelSelectValues.construct(
data.get("values", []),
data.get("resolved", {}),
state,
guild,
)
ClientT = TypeVar("ClientT", bound="Client")
MISSING: Any = _MissingSentinel()
ItemCallbackType = Callable[[Any, I, Interaction[ClientT]], Coroutine[Any, Any, Any]]
class ChannelType(IntEnum):
"""Specifies the type of channel."""
text = 0
"""A text channel"""
private = 1
"""A private text channel. Also called a direct message."""
voice = 2
"""A voice channel"""
group = 3
"""A private group text channel."""
category = 4
"""A category channel."""
news = 5
"""A guild news channel."""
news_thread = 10
"""A news thread."""
public_thread = 11
"""A public thread."""
private_thread = 12
"""A private thread."""
stage_voice = 13
"""A guild stage voice channel."""
guild_directory = 14
"""A channel containing the guilds in a
`Student Hub <https://support.discord.com/hc/en-us/articles/4406046651927-Discord-Student-Hubs-FAQ>`_
"""
forum = 15
"""A forum channel."""
def __str__(self) -> str:
return self.name
The provided code snippet includes necessary dependencies for implementing the `channel_select` function. Write a Python function `def channel_select( *, placeholder: Optional[str] = None, custom_id: str = MISSING, min_values: int = 1, max_values: int = 1, disabled: bool = False, row: Optional[int] = None, channel_types: List[ChannelType] = MISSING, ) -> Callable[ [ItemCallbackType[ChannelSelect[V_co], ClientT]], ItemCallbackType[ChannelSelect[V_co], ClientT] ]` to solve the following problem:
A decorator that attaches a channel select menu to a component. The function being decorated should have three parameters, ``self`` representing the :class:`.ui.View`, the :class:`.ui.ChannelSelect` being pressed and the :class:`.Interaction` you receive. In order to get the selected items that the user has chosen within the callback use :attr:`ChannelSelect.values`. .. versionadded:: 2.3 Parameters ---------- placeholder: Optional[:class:`str`] The placeholder text that is shown if nothing is selected, if any. custom_id: :class:`str` The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts. row: Optional[:class:`int`] The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed). min_values: :class:`int` The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. max_values: :class:`int` The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. disabled: :class:`bool` Whether the select is disabled or not. Defaults to ``False``. channel_types: List[:class:`.ChannelType`] A list of channel types that can be selected in this menu.
Here is the function:
def channel_select(
*,
placeholder: Optional[str] = None,
custom_id: str = MISSING,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False,
row: Optional[int] = None,
channel_types: List[ChannelType] = MISSING,
) -> Callable[
[ItemCallbackType[ChannelSelect[V_co], ClientT]], ItemCallbackType[ChannelSelect[V_co], ClientT]
]:
"""A decorator that attaches a channel select menu to a component.
The function being decorated should have three parameters, ``self`` representing
the :class:`.ui.View`, the :class:`.ui.ChannelSelect` being pressed and
the :class:`.Interaction` you receive.
In order to get the selected items that the user has chosen within the callback
use :attr:`ChannelSelect.values`.
.. versionadded:: 2.3
Parameters
----------
placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any.
custom_id: :class:`str`
The ID of the select menu that gets received during an interaction.
It is recommended not to set this parameter to prevent conflicts.
row: Optional[:class:`int`]
The relative row this select menu belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd
like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed).
min_values: :class:`int`
The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
max_values: :class:`int`
The maximum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
disabled: :class:`bool`
Whether the select is disabled or not. Defaults to ``False``.
channel_types: List[:class:`.ChannelType`]
A list of channel types that can be selected in this menu.
"""
def decorator(func: ItemCallbackType) -> ItemCallbackType:
if not asyncio.iscoroutinefunction(func):
raise TypeError("Select function must be a coroutine function")
func.__discord_ui_model_type__ = ChannelSelect
func.__discord_ui_model_kwargs__ = {
"placeholder": placeholder,
"custom_id": custom_id,
"row": row,
"min_values": min_values,
"max_values": max_values,
"disabled": disabled,
"channel_types": channel_types,
}
return func
return decorator | A decorator that attaches a channel select menu to a component. The function being decorated should have three parameters, ``self`` representing the :class:`.ui.View`, the :class:`.ui.ChannelSelect` being pressed and the :class:`.Interaction` you receive. In order to get the selected items that the user has chosen within the callback use :attr:`ChannelSelect.values`. .. versionadded:: 2.3 Parameters ---------- placeholder: Optional[:class:`str`] The placeholder text that is shown if nothing is selected, if any. custom_id: :class:`str` The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts. row: Optional[:class:`int`] The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed). min_values: :class:`int` The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. max_values: :class:`int` The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. disabled: :class:`bool` Whether the select is disabled or not. Defaults to ``False``. channel_types: List[:class:`.ChannelType`] A list of channel types that can be selected in this menu. |
160,979 | from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Callable, Generic, List, Optional, Tuple, TypeVar, Union
from ...components import SelectOption, StringSelectMenu
from ...emoji import Emoji
from ...enums import ComponentType
from ...interactions import ClientT
from ...partial_emoji import PartialEmoji
from ...utils import MISSING
from ..item import ItemCallbackType
from ..view import View
from .base import SelectBase
V_co = TypeVar("V_co", bound="View", covariant=True)
class StringSelect(SelectBase, Generic[V_co]):
"""Represents a UI string select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use :attr:`StringSelect.values`.
There is an alias for this class called ``Select``.
.. versionadded:: 2.0
Parameters
----------
custom_id: :class:`str`
The ID of the select menu that gets received during an interaction.
If not given then one is generated for you.
placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any.
min_values: :class:`int`
The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
max_values: :class:`int`
The maximum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
options: List[:class:`.SelectOption`]
A list of options that can be selected in this menu.
disabled: :class:`bool`
Whether the select is disabled or not.
row: Optional[:class:`int`]
The relative row this select menu belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd
like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed).
"""
__item_repr_attributes__: Tuple[str, ...] = (
"placeholder",
"min_values",
"max_values",
"options",
"disabled",
)
def __init__(
self,
*,
custom_id: str = MISSING,
placeholder: Optional[str] = None,
min_values: int = 1,
max_values: int = 1,
options: List[SelectOption] = MISSING,
disabled: bool = False,
row: Optional[int] = None,
) -> None:
super().__init__(
custom_id=custom_id,
min_values=min_values,
max_values=max_values,
disabled=disabled,
row=row,
placeholder=placeholder,
)
self._selected_values: List[str] = []
options = [] if options is MISSING else options
self._underlying = StringSelectMenu._raw_construct(
custom_id=self.custom_id,
type=ComponentType.select,
placeholder=self.placeholder,
min_values=self.min_values,
max_values=self.max_values,
disabled=self.disabled,
options=options,
)
def options(self) -> List[SelectOption]:
"""List[:class:`.SelectOption`]: A list of options that can be selected in this menu."""
return self._underlying.options
def options(self, value: List[SelectOption]) -> None:
if not isinstance(value, list):
raise TypeError("options must be a list of SelectOption")
if not all(isinstance(obj, SelectOption) for obj in value):
raise TypeError("All list items must subclass SelectOption")
self._underlying.options = value
def add_option(
self,
*,
label: str,
value: str = MISSING,
description: Optional[str] = None,
emoji: Optional[Union[str, Emoji, PartialEmoji]] = None,
default: bool = False,
) -> None:
"""Adds an option to the select menu.
To append a pre-existing :class:`.SelectOption` use the
:meth:`append_option` method instead.
Parameters
----------
label: :class:`str`
The label of the option. This is displayed to users.
Can only be up to 100 characters.
value: :class:`str`
The value of the option. This is not displayed to users.
If not given, defaults to the label. Can only be up to 100 characters.
description: Optional[:class:`str`]
An additional description of the option, if any.
Can only be up to 100 characters.
emoji: Optional[Union[:class:`str`, :class:`.Emoji`, :class:`.PartialEmoji`]]
The emoji of the option, if available. This can either be a string representing
the custom or unicode emoji or an instance of :class:`.PartialEmoji` or :class:`.Emoji`.
default: :class:`bool`
Whether this option is selected by default.
Raises
------
ValueError
The number of options exceeds 25.
"""
option = SelectOption(
label=label,
value=value,
description=description,
emoji=emoji,
default=default,
)
self.append_option(option)
def append_option(self, option: SelectOption) -> None:
"""Appends an option to the select menu.
Parameters
----------
option: :class:`.SelectOption`
The option to append to the select menu.
Raises
------
ValueError
The number of options exceeds 25.
"""
if len(self._underlying.options) > 25:
raise ValueError("maximum number of options already provided")
self._underlying.options.append(option)
def from_component(cls, component: StringSelectMenu) -> Self:
return cls(
custom_id=component.custom_id,
placeholder=component.placeholder,
min_values=component.min_values,
max_values=component.max_values,
options=component.options,
disabled=component.disabled,
row=None,
)
Select = StringSelect
class SelectOption:
"""Represents a select menu's option.
These can be created by users.
.. versionadded:: 2.0
Attributes
----------
label: :class:`str`
The label of the option. This is displayed to users.
Can only be up to 100 characters.
value: :class:`str`
The value of the option. This is not displayed to users.
If not provided when constructed then it defaults to the
label. Can only be up to 100 characters.
description: Optional[:class:`str`]
An additional description of the option, if any.
Can only be up to 100 characters.
emoji: Optional[Union[:class:`str`, :class:`Emoji`, :class:`PartialEmoji`]]
The emoji of the option, if available.
default: :class:`bool`
Whether this option is selected by default.
"""
__slots__: Tuple[str, ...] = (
"label",
"value",
"description",
"emoji",
"default",
)
def __init__(
self,
*,
label: str,
value: str = MISSING,
description: Optional[str] = None,
emoji: Optional[Union[str, Emoji, PartialEmoji]] = None,
default: bool = False,
) -> None:
self.label: str = label
self.value: str = label if value is MISSING else value
self.description: Optional[str] = description
if emoji is not None:
if isinstance(emoji, str):
emoji = PartialEmoji.from_str(emoji)
elif isinstance(emoji, _EmojiTag):
emoji = emoji._to_partial()
else:
raise TypeError(
f"Expected emoji to be str, Emoji, or PartialEmoji not {emoji.__class__}"
)
self.emoji: Optional[PartialEmoji] = emoji
self.default: bool = default
def __repr__(self) -> str:
return (
f"<SelectOption label={self.label!r} value={self.value!r} description={self.description!r} "
f"emoji={self.emoji!r} default={self.default!r}>"
)
def __str__(self) -> str:
base = f"{self.emoji} {self.label}" if self.emoji else self.label
if self.description:
return f"{base}\n{self.description}"
return base
def from_dict(cls, data: SelectOptionPayload) -> SelectOption:
try:
emoji = PartialEmoji.from_dict(data["emoji"])
except KeyError:
emoji = None
return cls(
label=data["label"],
value=data["value"],
description=data.get("description"),
emoji=emoji,
default=data.get("default", False),
)
def to_dict(self) -> SelectOptionPayload:
payload: SelectOptionPayload = {
"label": self.label,
"value": self.value,
"default": self.default,
}
if self.emoji:
payload["emoji"] = self.emoji.to_dict() # type: ignore
if self.description:
payload["description"] = self.description
return payload
ClientT = TypeVar("ClientT", bound="Client")
MISSING: Any = _MissingSentinel()
ItemCallbackType = Callable[[Any, I, Interaction[ClientT]], Coroutine[Any, Any, Any]]
The provided code snippet includes necessary dependencies for implementing the `string_select` function. Write a Python function `def string_select( *, placeholder: Optional[str] = None, custom_id: str = MISSING, min_values: int = 1, max_values: int = 1, options: List[SelectOption] = MISSING, disabled: bool = False, row: Optional[int] = None, ) -> Callable[ [ItemCallbackType[StringSelect[V_co], ClientT]], ItemCallbackType[StringSelect[V_co], ClientT] ]` to solve the following problem:
A decorator that attaches a string select menu to a component. There is an alias for this function called ``select``. The function being decorated should have three parameters, ``self`` representing the :class:`.ui.View`, the :class:`.ui.StringSelect` being pressed and the :class:`.Interaction` you receive. In order to get the selected items that the user has chosen within the callback use :attr:`StringSelect.values`. Parameters ---------- placeholder: Optional[:class:`str`] The placeholder text that is shown if nothing is selected, if any. custom_id: :class:`str` The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts. row: Optional[:class:`int`] The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed). min_values: :class:`int` The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. max_values: :class:`int` The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. options: List[:class:`.SelectOption`] A list of options that can be selected in this menu. disabled: :class:`bool` Whether the select is disabled or not. Defaults to ``False``.
Here is the function:
def string_select(
*,
placeholder: Optional[str] = None,
custom_id: str = MISSING,
min_values: int = 1,
max_values: int = 1,
options: List[SelectOption] = MISSING,
disabled: bool = False,
row: Optional[int] = None,
) -> Callable[
[ItemCallbackType[StringSelect[V_co], ClientT]], ItemCallbackType[StringSelect[V_co], ClientT]
]:
"""A decorator that attaches a string select menu to a component.
There is an alias for this function called ``select``.
The function being decorated should have three parameters, ``self`` representing
the :class:`.ui.View`, the :class:`.ui.StringSelect` being pressed and
the :class:`.Interaction` you receive.
In order to get the selected items that the user has chosen within the callback
use :attr:`StringSelect.values`.
Parameters
----------
placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any.
custom_id: :class:`str`
The ID of the select menu that gets received during an interaction.
It is recommended not to set this parameter to prevent conflicts.
row: Optional[:class:`int`]
The relative row this select menu belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd
like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed).
min_values: :class:`int`
The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
max_values: :class:`int`
The maximum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 1 and 25.
options: List[:class:`.SelectOption`]
A list of options that can be selected in this menu.
disabled: :class:`bool`
Whether the select is disabled or not. Defaults to ``False``.
"""
def decorator(
func: ItemCallbackType[Select[V_co], ClientT]
) -> ItemCallbackType[Select[V_co], ClientT]:
if not asyncio.iscoroutinefunction(func):
raise TypeError("Select function must be a coroutine function")
func.__discord_ui_model_type__ = StringSelect
func.__discord_ui_model_kwargs__ = {
"placeholder": placeholder,
"custom_id": custom_id,
"row": row,
"min_values": min_values,
"max_values": max_values,
"options": options,
"disabled": disabled,
}
return func
return decorator | A decorator that attaches a string select menu to a component. There is an alias for this function called ``select``. The function being decorated should have three parameters, ``self`` representing the :class:`.ui.View`, the :class:`.ui.StringSelect` being pressed and the :class:`.Interaction` you receive. In order to get the selected items that the user has chosen within the callback use :attr:`StringSelect.values`. Parameters ---------- placeholder: Optional[:class:`str`] The placeholder text that is shown if nothing is selected, if any. custom_id: :class:`str` The ID of the select menu that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts. row: Optional[:class:`int`] The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed). min_values: :class:`int` The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. max_values: :class:`int` The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25. options: List[:class:`.SelectOption`] A list of options that can be selected in this menu. disabled: :class:`bool` Whether the select is disabled or not. Defaults to ``False``. |
160,980 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
def _flatten_error_dict(d: Dict[str, Any], key: str = "") -> Dict[str, str]:
items: List[Tuple[str, str]] = []
for k, v in d.items():
new_key = key + "." + k if key else k
if isinstance(v, dict):
try:
_errors: List[Dict[str, Any]] = v["_errors"]
except KeyError:
items.extend(_flatten_error_dict(v, new_key).items())
else:
items.append((new_key, " ".join(x.get("message", "") for x in _errors)))
else:
items.append((new_key, v))
return dict(items) | null |
160,981 | from __future__ import annotations
from functools import reduce
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Iterator,
List,
Optional,
Tuple,
Type,
TypeVar,
overload,
)
from .enums import UserFlags
BF = TypeVar("BF", bound="BaseFlags")
class flag_value:
def __init__(self, func: Callable[[Any], int]) -> None:
self.flag = func(None)
self.__doc__ = func.__doc__
def __get__(self, instance: None, owner: Type[BF]) -> Self:
...
def __get__(self, instance: BF, owner: Type[BF]) -> bool:
...
def __get__(self, instance: Optional[BF], owner: Type[BF]) -> Any:
if instance is None:
return self
return instance._has_flag(self.flag)
def __set__(self, instance: BaseFlags, value: bool) -> None:
instance._set_flag(self.flag, value)
def __repr__(self) -> str:
return f"<flag_value flag={self.flag!r}>"
def fill_with_flags(*, inverted: bool = False):
def decorator(cls: Type[BF]):
cls.VALID_FLAGS = {
name: value.flag
for name, value in cls.__dict__.items()
if isinstance(value, flag_value)
}
if inverted:
max_bits = max(cls.VALID_FLAGS.values()).bit_length()
cls.DEFAULT_VALUE = -1 + (2**max_bits)
else:
cls.DEFAULT_VALUE = 0
return cls
return decorator | null |
160,982 | from __future__ import annotations
import argparse
import platform
import sys
from pathlib import Path
import aiohttp
import pkg_resources
import nextcord
def core(_parser, args) -> None:
if args.version:
show_version()
def add_newbot_args(subparser) -> None:
parser = subparser.add_parser("newbot", help="creates a command bot project quickly")
parser.set_defaults(func=newbot)
parser.add_argument("name", help="the bot project name")
parser.add_argument(
"directory", help="the directory to place it in (default: .)", nargs="?", default=Path.cwd()
)
parser.add_argument(
"--prefix", help="the bot prefix (default: $)", default="$", metavar="<prefix>"
)
parser.add_argument("--sharded", help="whether to use AutoShardedBot", action="store_true")
parser.add_argument(
"--no-git", help="do not create a .gitignore file", action="store_true", dest="no_git"
)
def add_newcog_args(subparser) -> None:
parser = subparser.add_parser("newcog", help="creates a new cog template quickly")
parser.set_defaults(func=newcog)
parser.add_argument("name", help="the cog name")
parser.add_argument(
"directory",
help="the directory to place it in (default: cogs)",
nargs="?",
default=Path("cogs"),
)
parser.add_argument(
"--class-name", help="the class name of the cog (default: <name>)", dest="class_name"
)
parser.add_argument("--display-name", help="the cog name (default: <name>)")
parser.add_argument(
"--hide-commands", help="whether to hide all commands in the cog", action="store_true"
)
parser.add_argument("--full", help="add all special methods as well", action="store_true")
def parse_args():
parser = argparse.ArgumentParser(prog="discord", description="Tools for helping with nextcord")
parser.add_argument("-v", "--version", action="store_true", help="shows the library version")
parser.set_defaults(func=core)
subparser = parser.add_subparsers(dest="subcommand", title="subcommands")
add_newbot_args(subparser)
add_newcog_args(subparser)
return parser, parser.parse_args() | null |
160,983 | from __future__ import annotations
import asyncio
import contextlib
import logging
import sys
import warnings
from inspect import Parameter, signature
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Coroutine,
Dict,
Iterable,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
import typing_extensions
from typing_extensions import Annotated
from .abc import GuildChannel
from .channel import (
CategoryChannel,
DMChannel,
ForumChannel,
GroupChannel,
StageChannel,
TextChannel,
VoiceChannel,
)
from .enums import ApplicationCommandOptionType, ApplicationCommandType, ChannelType, Locale
from .errors import (
ApplicationCheckFailure,
ApplicationCommandOptionMissing,
ApplicationError,
ApplicationInvokeError,
)
from .guild import Guild
from .interactions import Interaction
from .member import Member
from .message import Attachment, Message
from .object import Object
from .permissions import Permissions
from .role import Role
from .threads import Thread
from .types.interactions import ApplicationCommandInteractionData
from .user import User
from .utils import MISSING, find, maybe_coroutine, parse_docstring
FuncT = TypeVar("FuncT", bound=Callable[..., Any])
def _cog_special_method(func: FuncT) -> FuncT:
func.__cog_special_method__ = None
return func | null |
160,984 | from __future__ import annotations
import asyncio
import contextlib
import logging
import sys
import warnings
from inspect import Parameter, signature
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Coroutine,
Dict,
Iterable,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
import typing_extensions
from typing_extensions import Annotated
from .abc import GuildChannel
from .channel import (
CategoryChannel,
DMChannel,
ForumChannel,
GroupChannel,
StageChannel,
TextChannel,
VoiceChannel,
)
from .enums import ApplicationCommandOptionType, ApplicationCommandType, ChannelType, Locale
from .errors import (
ApplicationCheckFailure,
ApplicationCommandOptionMissing,
ApplicationError,
ApplicationInvokeError,
)
from .guild import Guild
from .interactions import Interaction
from .member import Member
from .message import Attachment, Message
from .object import Object
from .permissions import Permissions
from .role import Role
from .threads import Thread
from .types.interactions import ApplicationCommandInteractionData
from .user import User
from .utils import MISSING, find, maybe_coroutine, parse_docstring
class BaseApplicationCommand(CallbackMixin, CallbackWrapperMixin):
"""Base class for all application commands.
Attributes
----------
checks: List[Union[Callable[[:class:`ClientCog`, :class:`Interaction`], MaybeCoro[:class:`bool`]], Callable[[:class:`Interaction`], MaybeCoro[:class:`bool`]]]]
A list of predicates that verifies if the command could be executed
with the given :class:`Interaction` as the sole parameter. If an exception
is necessary to be thrown to signal failure, then one inherited from
:exc:`.ApplicationError` should be used. Note that if the checks fail then
:exc:`.ApplicationCheckFailure` exception is raised to the :func:`.on_application_command_error`
event.
"""
def __init__(
self,
name: Optional[str] = None,
description: Optional[str] = None,
*,
cmd_type: ApplicationCommandType,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
description_localizations: Optional[Dict[Union[Locale, str], str]] = None,
callback: Optional[Callable] = None,
guild_ids: Optional[Iterable[int]] = MISSING,
dm_permission: Optional[bool] = None,
default_member_permissions: Optional[Union[Permissions, int]] = None,
nsfw: bool = False,
parent_cog: Optional[ClientCog] = None,
force_global: bool = False,
) -> None:
"""Base application command class that all specific application command classes should subclass. All common
behavior should be here, with subclasses either adding on or overriding specific aspects of this class.
Parameters
----------
cmd_type: :class:`ApplicationCommandType`
Type of application command. This should be set by subclasses.
name: :class:`str`
Name of the command.
description: :class:`str`
Description of the command.
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the command for users of specific locales. The locale code should be the key, with the localized
name as the value.
description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Description(s) of the command for users of specific locales. The locale code should be the key, with the
localized description as the value.
callback: :data:`~typing.Callable`
Callback to make the application command from, and to run when the application command is called.
guild_ids: Iterable[:class:`int`]
An iterable list/set/whatever of guild ID's that the application command should register to.
If not passed and :attr:`Client.default_guild_ids` is set, then those default guild ids will
be used instead. If both of those are unset, then the command will be a global command.
dm_permission: :class:`bool`
If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being
usable in DMs. Only for global commands, but will not error on guild.
default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]]
Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for
example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by
default. Server owners CAN override the permission requirements.
nsfw: :class:`bool`
Whether the command can only be used in age-restricted channels. Defaults to ``False``.
.. versionadded:: 2.4
parent_cog: Optional[:class:`ClientCog`]
``ClientCog`` to forward to the callback as the ``self`` argument.
force_global: :class:`bool`
If this command should be registered as a global command, ALONG WITH all guild IDs set.
"""
CallbackWrapperMixin.__init__(self, callback)
CallbackMixin.__init__(self, callback=callback, parent_cog=parent_cog)
self._state: Optional[ConnectionState] = None
self.type = cmd_type or ApplicationCommandType(1)
self.name: Optional[str] = name
self.name_localizations: Optional[Dict[Union[str, Locale], str]] = name_localizations
self._description: Optional[str] = description
self.description_localizations: Optional[
Dict[Union[str, Locale], str]
] = description_localizations
self.guild_ids_to_rollout: Set[int] = set(guild_ids) if guild_ids else set()
self.use_default_guild_ids: bool = guild_ids is MISSING and not force_global
self.dm_permission: Optional[bool] = dm_permission
self.default_member_permissions: Optional[
Union[Permissions, int]
] = default_member_permissions
self.nsfw: bool = nsfw
self.force_global: bool = force_global
self.command_ids: Dict[Optional[int], int] = {}
"""
Dict[Optional[:class:`int`], :class:`int`]:
Command IDs that this application command currently has. Schema: {Guild ID (None for global): command ID}
"""
self.options: Dict[str, ApplicationCommandOption] = {}
# Simple-ish getter + setter methods.
def required_permissions(self) -> Dict[str, bool]:
"""Returns the permissions required to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_permissions", {})
def required_bot_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.bot_has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_bot_permissions", {})
def required_guild_permissions(self) -> Dict[str, bool]:
"""Returns the guild permissions needed to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_guild_permissions", {})
def required_bot_guild_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to have in this guild in order to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.bot_has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_bot_guild_permissions", {})
def qualified_name(self) -> str:
""":class:`str`: Retrieves the fully qualified command name.
.. versionadded:: 2.1
"""
return str(self.name)
def description(self) -> str:
"""The description the command should have in Discord. Should be 1-100 characters long."""
return self._description or DEFAULT_SLASH_DESCRIPTION
def description(self, new_description: str) -> None:
self._description = new_description
def is_guild(self) -> bool:
""":class:`bool`: Returns ``True`` if this command is or should be registered to any guilds."""
guild_only_ids = set(self.command_ids.keys())
guild_only_ids.discard(None)
return bool(self.guild_ids_to_rollout or guild_only_ids)
def guild_ids(self) -> Set[int]:
"""Returns a :class:`set` containing all guild ID's this command is registered to."""
# TODO: Is this worthwhile?
guild_only_ids = set(self.command_ids.keys())
guild_only_ids.discard(None)
# ignore explanation: Mypy says that guild_only_ids can contain None due to self.command_ids.keys() having
# None being typehinted, but we remove None before returning it.
return guild_only_ids # type: ignore
def add_guild_rollout(self, guild: Union[int, Guild]) -> None:
"""Adds a Guild to the command to be rolled out to when the rollout is run.
Parameters
----------
guild: Union[:class:`int`, :class:`Guild`]
Guild or Guild ID to add this command to roll out to.
"""
self.guild_ids_to_rollout.add(guild.id if isinstance(guild, Guild) else guild)
def is_global(self) -> bool:
""":class:`bool`: Returns ``True`` if this command is or should be a global command."""
return self.force_global or not self.is_guild or None in self.command_ids
def get_signature(
self, guild_id: Optional[int] = None
) -> Tuple[Optional[str], int, Optional[int]]:
"""Returns a command signature with the given guild ID.
Parameters
----------
guild_id: Optional[:class:`None`]
Guild ID to make the signature for. If set to ``None``, it acts as a global command signature.
Returns
-------
Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]
A tuple that acts as a signature made up of the name, type, and guild ID.
"""
# noinspection PyUnresolvedReferences
return self.name, self.type.value, guild_id
def get_rollout_signatures(self) -> Set[Tuple[str, int, Optional[int]]]:
"""Returns all signatures that this command wants to roll out to.
Command signatures are made up of the command name, command type, and Guild ID (``None`` for global).
Returns
-------
Set[Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]]
A set of tuples that act as signatures.
"""
ret = set()
if self.is_global:
ret.add(self.get_signature(None))
for guild_id in self.guild_ids_to_rollout:
ret.add(self.get_signature(guild_id))
return ret
def get_signatures(self) -> Set[Tuple[str, int, Optional[int]]]:
"""Returns all the signatures that this command has.
Command signatures are made up of the command name, command type, and Guild ID (``None`` for global).
Returns
-------
Set[Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]]
A set of tuples that act as signatures.
"""
ret = set()
if self.is_global:
ret.add(self.get_signature(None))
if self.is_guild:
for guild_id in self.guild_ids:
ret.add(self.get_signature(guild_id))
return ret
def get_name_localization_payload(self) -> Optional[Dict[str, str]]:
if self.name_localizations:
ret = {}
for locale, name in self.name_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = name
else:
ret[locale] = name
return ret
return None
def get_description_localization_payload(self) -> Optional[dict]:
if self.description_localizations:
ret = {}
for locale, description in self.description_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = description
else:
ret[locale] = description
return ret
return None
def get_default_member_permissions_value(self) -> Optional[int]:
if (
isinstance(self.default_member_permissions, int)
or self.default_member_permissions is None
):
return self.default_member_permissions
return self.default_member_permissions.value
def get_payload(self, guild_id: Optional[int]) -> dict:
"""Makes an Application Command payload for this command to upsert to Discord with the given Guild ID.
Parameters
----------
guild_id: Optional[:class:`int`]
Guild ID that this payload is for. If set to ``None``, it will be a global command payload instead.
Returns
-------
:class:`dict`
Dictionary payload to upsert to Discord.
"""
# Below is to make PyCharm stop complaining that self.type.value isn't valid.
# noinspection PyUnresolvedReferences
ret = {
"type": self.type.value,
"name": str(
self.name
), # Might as well stringify the name, will come in handy if people try using numbers.
"description": str(self.description), # Might as well do the same with the description.
"name_localizations": self.get_name_localization_payload(),
"description_localizations": self.get_description_localization_payload(),
}
if self.default_member_permissions is not None:
# While Discord accepts it as an int, they will respond back with the permissions value as a string because
# the permissions bitfield can get too big for them. Stringify it for easy payload-comparison.
ret["default_member_permissions"] = str(self.get_default_member_permissions_value())
if guild_id: # Guild-command specific payload options.
ret["guild_id"] = guild_id
# Global command specific payload options.
elif self.dm_permission is not None:
ret["dm_permission"] = self.dm_permission
else:
# Discord seems to send back the DM permission as True regardless if we sent it or not, so we send as
# the default (True) to ensure payload parity for comparisons.
ret["dm_permission"] = True
ret["nsfw"] = self.nsfw
return ret
def parse_discord_response(
self,
state: ConnectionState,
data: Union[ApplicationCommandInteractionData, ApplicationCommandPayload],
) -> None:
"""Parses the application command creation/update response from Discord.
Parameters
----------
state: :class:`ConnectionState`
Connection state to use internally in the command.
data: Union[:class:`ApplicationCommandInteractionData`, :class:`ApplicationCommand`]
Raw dictionary data from Discord.
"""
self._state = state
command_id = int(data["id"])
if guild_id := data.get("guild_id", None):
guild_id = int(guild_id)
self.command_ids[guild_id] = command_id
self.guild_ids_to_rollout.add(guild_id)
else:
self.command_ids[None] = command_id
def is_payload_valid(
self, raw_payload: ApplicationCommandPayload, guild_id: Optional[int] = None
) -> bool:
"""Checks if the given raw application command interaction payload from Discord is possibly valid for
this command.
Note that while this may return ``True`` for a given payload, that doesn't mean that the payload is fully
correct for this command. Discord doesn't send data for parameters that are optional and aren't supplied by
the user.
Parameters
----------
raw_payload: :class:`dict`
Application command interaction payload from Discord.
guild_id: Optional[:class:`int`]
Guild ID that the payload is from. If it's from a global command, this should be ``None``
Returns
-------
:class:`bool`
``True`` if the given payload is possibly valid for this command. ``False`` otherwise.
"""
cmd_payload = self.get_payload(guild_id)
if cmd_payload.get("guild_id", 0) != int(raw_payload.get("guild_id", 0)):
_log.debug("Guild ID doesn't match raw payload, not valid payload.")
return False
if not check_dictionary_values(
cmd_payload,
raw_payload, # type: ignore # specificity of typeddicts doesnt matter in validation
"default_member_permissions",
"description",
"type",
"name",
"name_localizations",
"description_localizations",
"dm_permission",
"nsfw",
):
_log.debug("Failed check dictionary values, not valid payload.")
return False
if len(cmd_payload.get("options", [])) != len(raw_payload.get("options", [])):
_log.debug("Option amount between commands not equal, not valid payload.")
return False
for cmd_option in cmd_payload.get("options", []):
# I absolutely do not trust Discord or us ordering things nicely, so check through both.
found_correct_value = False
for raw_option in raw_payload.get("options", []):
if cmd_option["name"] == raw_option["name"]:
found_correct_value = True
# At this time, ApplicationCommand options are identical between locally-generated payloads and
# payloads from Discord. If that were to change, switch from a recursive setup and manually
# check_dictionary_values.
if not deep_dictionary_check(cmd_option, raw_option): # type: ignore
# its a dict check so typeddicts do not matter
_log.debug("Options failed deep dictionary checks, not valid payload.")
return False
break
if not found_correct_value:
_log.debug("Discord is missing an option we have, not valid payload.")
return False
return True
def is_interaction_valid(self, interaction: Interaction) -> bool:
"""Checks if the interaction given is possibly valid for this command.
If the command has more parameters (especially optionals) than the interaction coming in, this may cause a
desync between your bot and Discord.
Parameters
----------
interaction: :class:`Interaction`
Interaction to validate.
Returns
-------
:class:`bool`
``True`` If the interaction could possibly be for this command, ``False`` otherwise.
"""
data = interaction.data
if data is None:
raise ValueError("Discord did not provide us with interaction data")
our_payload = self.get_payload(data.get("guild_id", None))
def _recursive_subcommand_check(inter_pos: dict, cmd_pos: dict) -> bool:
"""A small recursive wrapper that checks for subcommand(s) (group(s)).
Parameters
----------
inter_pos: :class:`dict`
Current command position from the payload in the interaction.
cmd_pos: :class:`dict`
Current command position from the payload for the local command.
Returns
-------
:class:`bool`
``True`` if the payloads match, ``False`` otherwise.
"""
inter_options = inter_pos.get("options")
cmd_options = cmd_pos.get("options", {})
if inter_options is None:
raise ValueError("Interaction options was not provided")
our_options = {opt["name"]: opt for opt in cmd_options}
if (
len(inter_options) == 1
and ( # If the length is only 1, it might be a subcommand (group).
inter_options[0]["type"]
in (
ApplicationCommandOptionType.sub_command.value,
ApplicationCommandOptionType.sub_command_group.value,
)
)
and ( # This checks if it's a subcommand (group).
found_opt := our_options.get(
inter_options[0]["name"]
) # This checks if the name matches an option.
)
and inter_options[0]["type"] == found_opt["type"]
): # And this makes sure both are the same type.
return _recursive_subcommand_check(
inter_options[0], found_opt
) # If all of the above pass, recurse.
return _option_check(inter_options, cmd_options)
def _option_check(inter_options: dict, cmd_options: dict) -> bool:
"""Checks if the two given command payloads have matching options.
Parameters
----------
inter_options: :class:`dict`
Command option data from the interaction.
cmd_options: :class:`dict`
Command option data from the local command.
Returns
-------
:class:`bool`
``True`` if the options match, ``False`` otherwise.
"""
all_our_options = {}
required_options = {}
for our_opt in cmd_options:
all_our_options[our_opt["name"]] = our_opt
if our_opt.get("required"):
required_options[our_opt["name"]] = our_opt
all_inter_options = {inter_opt["name"]: inter_opt for inter_opt in inter_options}
if len(all_our_options) >= len(all_inter_options):
# If we have more options (including options) than the interaction, we are good to proceed.
all_our_options_copy = all_our_options.copy()
all_inter_options_copy = all_inter_options.copy()
# Begin checking required options.
for our_opt_name, our_opt in required_options.items():
if inter_opt := all_inter_options.get(our_opt_name):
if (
inter_opt["name"] == our_opt["name"]
and inter_opt["type"] == our_opt["type"]
):
all_our_options_copy.pop(our_opt_name)
all_inter_options_copy.pop(our_opt_name)
else:
_log.debug(
"%s Required option don't match name and/or type.", self.error_name
)
return False # Options don't match name and/or type.
else:
_log.debug("%s Inter missing required option.", self.error_name)
return False # Required option wasn't found.
# Begin checking optional arguments.
for (
inter_opt_name,
inter_opt,
) in all_inter_options_copy.items(): # Should only contain optionals now.
if our_opt := all_our_options_copy.get(inter_opt_name):
if not (
inter_opt["name"] == our_opt["name"]
and inter_opt["type"] == our_opt["type"]
):
_log.debug(
"%s Optional option don't match name and/or type.", self.error_name
)
return False # Options don't match name and/or type.
else:
_log.debug("%s Inter has option that we don't.", self.error_name)
return False # They have an option name that we don't.
else:
_log.debug(
"%s We have less options than them: %s vs %s",
self.error_name,
all_our_options,
all_inter_options,
)
return False # Interaction has more options than we do.
return True # No checks failed.
# caring about typeddict specificity will cause issues down the line
if not check_dictionary_values(our_payload, data, "name", "guild_id", "type"): # type: ignore
_log.debug("%s Failed basic dictionary check.", self.error_name)
return False
data_options = data.get("options")
payload_options = our_payload.get("options")
if data_options and payload_options:
return _recursive_subcommand_check(data, our_payload) # type: ignore
if data_options is None and payload_options is None:
return True # User and Message commands don't have options.
_log.debug(
"%s Mismatch between data and payload options: %s vs %s",
self.error_name,
data_options,
payload_options,
)
# There is a mismatch between the two, fail it.
return False
def from_callback(
self,
callback: Optional[Callable] = None,
option_class: Optional[Type[BaseCommandOption]] = BaseCommandOption,
) -> None:
super().from_callback(callback=callback, option_class=option_class)
async def call_from_interaction(self, interaction: Interaction) -> None:
"""|coro|
Calls the callback via the given :class:`Interaction`, relying on the locally
stored :class:`ConnectionState` object.
Parameters
----------
interaction: :class:`Interaction`
Interaction corresponding to the use of the command.
"""
await self.call(self._state, interaction) # type: ignore
async def call(self, state: ConnectionState, interaction: Interaction) -> None:
"""|coro|
Calls the callback via the given :class:`Interaction`, using the given :class:`ConnectionState` to get resolved
objects if needed and available.
Parameters
----------
state: :class:`ConnectionState`
State object to get resolved objects from.
interaction: :class:`Interaction`
Interaction corresponding to the use of the command.
"""
raise NotImplementedError
def check_against_raw_payload(
self, raw_payload: ApplicationCommandPayload, guild_id: Optional[int] = None
) -> bool:
warnings.warn(
".check_against_raw_payload() is deprecated, please use .is_payload_valid instead.",
stacklevel=2,
category=FutureWarning,
)
return self.is_payload_valid(raw_payload, guild_id)
def get_guild_payload(self, guild_id: int):
warnings.warn(
".get_guild_payload is deprecated, use .get_payload(guild_id) instead.",
stacklevel=2,
category=FutureWarning,
)
return self.get_payload(guild_id)
def global_payload(self) -> dict:
warnings.warn(
".global_payload is deprecated, use .get_payload(None) instead.",
stacklevel=2,
category=FutureWarning,
)
return self.get_payload(None)
class SlashApplicationCommand(SlashCommandMixin, BaseApplicationCommand, AutocompleteCommandMixin):
"""Class representing a slash command."""
def __init__(
self,
name: Optional[str] = None,
description: Optional[str] = None,
*,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
description_localizations: Optional[Dict[Union[Locale, str], str]] = None,
callback: Optional[Callable] = None,
guild_ids: Optional[Iterable[int]] = None,
dm_permission: Optional[bool] = None,
default_member_permissions: Optional[Union[Permissions, int]] = None,
nsfw: bool = False,
parent_cog: Optional[ClientCog] = None,
force_global: bool = False,
) -> None:
"""Represents a Slash Application Command built from the given callback, able to be registered to multiple
guilds or globally.
Parameters
----------
name: :class:`str`
Name of the command. Must be lowercase with no spaces.
description: :class:`str`
Description of the command. Must be between 1 to 100 characters, or defaults to a set string.
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the subcommand for users of specific locales. The locale code should be the key, with the
localized name as the value.
description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Description(s) of the subcommand for users of specific locales. The locale code should be the key, with the
localized description as the value.
callback: :data:`~typing.Callable`
Callback to make the application command from, and to run when the application command is called.
guild_ids: Iterable[:class:`int`]
An iterable list of guild ID's that the application command should register to.
dm_permission: :class:`bool`
If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being
usable in DMs. Only for global commands.
default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]]
Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for
example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by
default. Server owners CAN override the permission requirements.
nsfw: :class:`bool`
Whether the command can only be used in age-restricted channels. Defaults to ``False``.
.. note::
Due to a discord limitation, this can only be set for the parent command in case of a subcommand.
.. versionadded:: 2.4
parent_cog: Optional[:class:`ClientCog`]
``ClientCog`` to forward to the callback as the ``self`` argument.
force_global: :class:`bool`
If this command should be registered as a global command, ALONG WITH all guild IDs set.
"""
BaseApplicationCommand.__init__(
self,
name=name,
name_localizations=name_localizations,
description=description,
description_localizations=description_localizations,
callback=callback,
cmd_type=ApplicationCommandType.chat_input,
guild_ids=guild_ids,
default_member_permissions=default_member_permissions,
dm_permission=dm_permission,
nsfw=nsfw,
parent_cog=parent_cog,
force_global=force_global,
)
AutocompleteCommandMixin.__init__(self, parent_cog=parent_cog)
SlashCommandMixin.__init__(self, callback=callback, parent_cog=parent_cog)
def description(self) -> str:
return super().description # Required to grab the correct description function.
def description(self, new_desc: str) -> None:
self._description = new_desc
def get_payload(self, guild_id: Optional[int]):
ret = super().get_payload(guild_id)
if self.children:
ret["options"] = [child.payload for child in self.children.values()]
elif self.options:
ret["options"] = [parameter.payload for parameter in self.options.values()]
return ret
async def call(self, state: ConnectionState, interaction: Interaction) -> None:
if interaction.data is None:
raise ValueError("Discord did not provide us interaction data")
# pyright does not want to lose typeddict specificity but we do not care here
option_data = interaction.data.get("options", [])
if self.children:
if not option_data:
raise ValueError("Discord did not provide us any options data")
await self.children[option_data[0]["name"]].call(
state, interaction, option_data[0].get("options", [])
)
else:
await self.call_slash(state, interaction, option_data)
def from_callback(
self,
callback: Optional[Callable] = None,
option_class: Type[SlashCommandOption] = SlashCommandOption,
call_children: bool = True,
) -> None:
BaseApplicationCommand.from_callback(self, callback=callback, option_class=option_class)
SlashCommandMixin.from_callback(self, callback=callback)
AutocompleteCommandMixin.from_autocomplete(self)
if call_children and self.children:
for child in self.children.values():
child.from_callback(
callback=child.callback, option_class=option_class, call_children=call_children
)
CallbackWrapperMixin.modify(self)
def subcommand(
self,
name: Optional[str] = None,
description: Optional[str] = None,
*,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
description_localizations: Optional[Dict[Union[Locale, str], str]] = None,
inherit_hooks: bool = False,
) -> Callable[[Callable], SlashApplicationSubcommand]:
"""Takes the decorated callback and turns it into a :class:`SlashApplicationSubcommand` added as a subcommand.
Parameters
----------
name: :class:`str`
Name of the command that users will see. If not set, it defaults to the name of the callback.
description: :class:`str`
Description of the command that users will see. If not specified, the docstring will be used.
If no docstring is found for the command callback, it defaults to "No description provided".
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the command for users of specific locales. The locale code should be the key, with the localized
name as the value.
description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Description(s) of the subcommand for users of specific locales. The locale code should be the key, with the
localized description as the value.
inherit_hooks: :class:`bool`
If the subcommand should inherit the parent commands ``before_invoke`` and ``after_invoke`` callbacks.
Defaults to ``False``.
"""
def decorator(func: Callable) -> SlashApplicationSubcommand:
ret = SlashApplicationSubcommand(
name=name,
name_localizations=name_localizations,
description=description,
description_localizations=description_localizations,
callback=func,
parent_cmd=self,
cmd_type=ApplicationCommandOptionType.sub_command,
parent_cog=self.parent_cog,
inherit_hooks=inherit_hooks,
)
self.children[
ret.name
or (func.callback.__name__ if isinstance(func, CallbackWrapper) else func.__name__)
] = ret
return ret
return decorator
class Locale(StrEnum):
da = "da"
"""Danish | Dansk"""
de = "de"
"""German | Deutsch"""
en_GB = "en-GB"
"""English, UK | English, UK"""
en_US = "en-US"
"""English, US | English, US"""
es_ES = "es-ES"
"""Spanish | Español"""
fr = "fr"
"""French | Français"""
hr = "hr"
"""Croatian | Hrvatski"""
id = "id"
"""Indonesian | Bahasa Indonesia
.. versionadded:: 2.4
"""
it = "it"
"""Italian | Italiano"""
lt = "lt"
"""Lithuanian | Lietuviškai"""
hu = "hu"
"""Hungarian | Magyar"""
nl = "nl"
"""Dutch | Nederlands"""
no = "no"
"""Norwegian | Norsk"""
pl = "pl"
"""Polish | Polski"""
pt_BR = "pt-BR"
"""Portuguese, Brazilian | Português do Brasil"""
ro = "ro"
"""Romanian, Romania | Română"""
fi = "fi"
"""Finnish | Suomi"""
sv_SE = "sv-SE"
"""Swedish | Svenska"""
vi = "vi"
"""Vietnamese | Tiếng Việt"""
tr = "tr"
"""Turkish | Türkçe"""
cs = "cs"
"""Czech | Čeština"""
el = "el"
"""Greek | Ελληνικά"""
bg = "bg"
"""Bulgarian | български"""
ru = "ru"
"""Russian | Pусский""" # noqa: RUF001
uk = "uk"
"""Ukrainian | Українська"""
hi = "hi"
"""Hindi | हिन्दी"""
th = "th"
"""Thai | ไทย"""
zh_CN = "zh-CN"
"""Chinese, China | 中文"""
ja = "ja"
"""Japanese | 日本語"""
zh_TW = "zh-TW"
"""Chinese, Taiwan | 繁體中文"""
ko = "ko"
"""Korean | 한국어"""
class Permissions(BaseFlags):
"""Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual
bits using the properties as if they were regular bools. This allows
you to edit permissions.
.. versionchanged:: 1.3
You can now use keyword arguments to initialize :class:`Permissions`
similar to :meth:`update`.
.. container:: operations
.. describe:: x == y
Checks if two permissions are equal.
.. describe:: x != y
Checks if two permissions are not equal.
.. describe:: x <= y
Checks if a permission is a subset of another permission.
.. describe:: x >= y
Checks if a permission is a superset of another permission.
.. describe:: x < y
Checks if a permission is a strict subset of another permission.
.. describe:: x > y
Checks if a permission is a strict superset of another permission.
.. describe:: hash(x)
Return the permission's hash.
.. describe:: iter(x)
Returns an iterator of ``(perm, value)`` pairs. This allows it
to be, for example, constructed as a dict or a list of pairs.
Note that aliases are not shown.
Attributes
----------
value: :class:`int`
The raw value. This value is a bit array field of a 53-bit integer
representing the currently available permissions. You should query
permissions via the properties rather than using this raw value.
"""
__slots__ = ()
def __init__(self, permissions: int = 0, **kwargs: bool) -> None:
if not isinstance(permissions, int):
raise TypeError(
f"Expected int parameter, received {permissions.__class__.__name__} instead."
)
self.value = permissions
for key, value in kwargs.items():
if key not in self.VALID_FLAGS:
raise TypeError(f"{key!r} is not a valid permission name.")
setattr(self, key, value)
def is_subset(self, other: Permissions) -> bool:
"""Returns ``True`` if self has the same or fewer permissions as other."""
if isinstance(other, Permissions):
return (self.value & other.value) == self.value
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}")
def is_superset(self, other: Permissions) -> bool:
"""Returns ``True`` if self has the same or more permissions as other."""
if isinstance(other, Permissions):
return (self.value | other.value) == self.value
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}")
def is_strict_subset(self, other: Permissions) -> bool:
"""Returns ``True`` if the permissions on other are a strict subset of those on self."""
return self.is_subset(other) and self != other
def is_strict_superset(self, other: Permissions) -> bool:
"""Returns ``True`` if the permissions on other are a strict superset of those on self."""
return self.is_superset(other) and self != other
__le__ = is_subset
__ge__ = is_superset
__lt__ = is_strict_subset
__gt__ = is_strict_superset
def none(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
permissions set to ``False``."""
return cls(0)
def all(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
permissions set to ``True``.
"""
return cls(-1)
def all_channel(cls) -> Self:
"""A :class:`Permissions` with all channel-specific permissions set to
``True`` and the guild-specific ones set to ``False``. The guild-specific
permissions are currently:
- :attr:`manage_emojis`
- :attr:`view_audit_log`
- :attr:`view_guild_insights`
- :attr:`manage_guild`
- :attr:`change_nickname`
- :attr:`manage_nicknames`
- :attr:`kick_members`
- :attr:`ban_members`
- :attr:`administrator`
.. versionchanged:: 1.7
Added :attr:`stream`, :attr:`priority_speaker` and :attr:`use_slash_commands` permissions.
.. versionchanged:: 2.0
Added :attr:`create_public_threads`, :attr:`create_private_threads`, :attr:`manage_threads`,
:attr:`use_external_stickers`, :attr:`send_messages_in_threads` and
:attr:`request_to_speak` permissions.
"""
return cls(0b111110110110011111101111111111101010001)
def general(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"General" permissions from the official Discord UI set to ``True``.
.. versionchanged:: 1.7
Permission :attr:`read_messages` is now included in the general permissions, but
permissions :attr:`administrator`, :attr:`create_instant_invite`, :attr:`kick_members`,
:attr:`ban_members`, :attr:`change_nickname` and :attr:`manage_nicknames` are
no longer part of the general permissions.
"""
return cls(0b01110000000010000000010010110000)
def membership(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Membership" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(0b00001100000000000000000000000111)
def text(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Text" permissions from the official Discord UI set to ``True``.
.. versionchanged:: 1.7
Permission :attr:`read_messages` is no longer part of the text permissions.
Added :attr:`use_slash_commands` permission.
.. versionchanged:: 2.0
Added :attr:`create_public_threads`, :attr:`create_private_threads`, :attr:`manage_threads`,
:attr:`send_messages_in_threads` and :attr:`use_external_stickers` permissions.
"""
return cls(0b111110010000000000001111111100001000000)
def voice(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Voice" permissions from the official Discord UI set to ``True``."""
return cls(0b00000011111100000000001100000000)
def stage(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Stage Channel" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(1 << 32)
def stage_moderator(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Stage Moderator" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(0b100000001010000000000000000000000)
def advanced(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Advanced" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(1 << 3)
def update(self, **kwargs: bool) -> None:
r"""Bulk updates this permission object.
Allows you to set multiple attributes by using keyword
arguments. The names must be equivalent to the properties
listed. Extraneous key/value pairs will be silently ignored.
Parameters
----------
\*\*kwargs
A list of key/value pairs to bulk update permissions with.
"""
for key, value in kwargs.items():
if key in self.VALID_FLAGS:
setattr(self, key, value)
def handle_overwrite(self, allow: int, deny: int) -> None:
# Basically this is what's happening here.
# We have an original bit array, e.g. 1010
# Then we have another bit array that is 'denied', e.g. 1111
# And then we have the last one which is 'allowed', e.g. 0101
# We want original OP denied to end up resulting in
# whatever is in denied to be set to 0.
# So 1010 OP 1111 -> 0000
# Then we take this value and look at the allowed values.
# And whatever is allowed is set to 1.
# So 0000 OP2 0101 -> 0101
# The OP is base & ~denied.
# The OP2 is base | allowed.
self.value = (self.value & ~deny) | allow
def create_instant_invite(self) -> int:
""":class:`bool`: Returns ``True`` if the user can create instant invites."""
return 1 << 0
def kick_members(self) -> int:
""":class:`bool`: Returns ``True`` if the user can kick users from the guild."""
return 1 << 1
def ban_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can ban users from the guild."""
return 1 << 2
def administrator(self) -> int:
""":class:`bool`: Returns ``True`` if a user is an administrator. This role overrides all other permissions.
This also bypasses all channel-specific overrides.
"""
return 1 << 3
def manage_channels(self) -> int:
""":class:`bool`: Returns ``True`` if a user can edit, delete, or create channels in the guild.
This also corresponds to the "Manage Channel" channel-specific override."""
return 1 << 4
def manage_guild(self) -> int:
""":class:`bool`: Returns ``True`` if a user can edit guild properties."""
return 1 << 5
def add_reactions(self) -> int:
""":class:`bool`: Returns ``True`` if a user can add reactions to messages."""
return 1 << 6
def view_audit_log(self) -> int:
""":class:`bool`: Returns ``True`` if a user can view the guild's audit log."""
return 1 << 7
def priority_speaker(self) -> int:
""":class:`bool`: Returns ``True`` if a user can be more easily heard while talking."""
return 1 << 8
def stream(self) -> int:
""":class:`bool`: Returns ``True`` if a user can stream in a voice channel."""
return 1 << 9
def read_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can read messages from all or specific text channels."""
return 1 << 10
def view_channel(self) -> int:
""":class:`bool`: An alias for :attr:`read_messages`.
.. versionadded:: 1.3
"""
return 1 << 10
def send_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send messages from all or specific text channels.
This falls under ``Create Posts`` on the UI specifically for Forum Channels.
"""
return 1 << 11
def send_tts_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send TTS messages from all or specific text channels."""
return 1 << 12
def manage_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can delete or pin messages in a text channel.
.. note::
Note that there are currently no ways to edit other people's messages.
"""
return 1 << 13
def embed_links(self) -> int:
""":class:`bool`: Returns ``True`` if a user's messages will automatically be embedded by Discord."""
return 1 << 14
def attach_files(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send files in their messages."""
return 1 << 15
def read_message_history(self) -> int:
""":class:`bool`: Returns ``True`` if a user can read a text channel's previous messages."""
return 1 << 16
def mention_everyone(self) -> int:
""":class:`bool`: Returns ``True`` if a user's @everyone or @here will mention everyone in the text channel."""
return 1 << 17
def external_emojis(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use emojis from other guilds."""
return 1 << 18
def use_external_emojis(self) -> int:
""":class:`bool`: An alias for :attr:`external_emojis`.
.. versionadded:: 1.3
"""
return 1 << 18
def view_guild_insights(self) -> int:
""":class:`bool`: Returns ``True`` if a user can view the guild's insights.
.. versionadded:: 1.3
"""
return 1 << 19
def connect(self) -> int:
""":class:`bool`: Returns ``True`` if a user can connect to a voice channel."""
return 1 << 20
def speak(self) -> int:
""":class:`bool`: Returns ``True`` if a user can speak in a voice channel."""
return 1 << 21
def mute_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can mute other users."""
return 1 << 22
def deafen_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can deafen other users."""
return 1 << 23
def move_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can move users between other voice channels."""
return 1 << 24
def use_voice_activation(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use voice activation in voice channels."""
return 1 << 25
def change_nickname(self) -> int:
""":class:`bool`: Returns ``True`` if a user can change their nickname in the guild."""
return 1 << 26
def manage_nicknames(self) -> int:
""":class:`bool`: Returns ``True`` if a user can change other user's nickname in the guild."""
return 1 << 27
def manage_roles(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create or edit roles less than their role's position.
This also corresponds to the "Manage Permissions" channel-specific override.
"""
return 1 << 28
def manage_permissions(self) -> int:
""":class:`bool`: An alias for :attr:`manage_roles`.
.. versionadded:: 1.3
"""
return 1 << 28
def manage_webhooks(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create, edit, or delete webhooks."""
return 1 << 29
def manage_emojis(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create, edit, or delete emojis."""
return 1 << 30
def manage_emojis_and_stickers(self) -> int:
""":class:`bool`: An alias for :attr:`manage_emojis`.
.. versionadded:: 2.0
"""
return 1 << 30
def use_slash_commands(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use slash commands.
.. versionadded:: 1.7
"""
return 1 << 31
def request_to_speak(self) -> int:
""":class:`bool`: Returns ``True`` if a user can request to speak in a stage channel.
.. versionadded:: 1.7
"""
return 1 << 32
def manage_events(self) -> int:
""":class:`bool`: Returns ``True`` if a user can manage guild events.
.. versionadded:: 2.0
"""
return 1 << 33
def manage_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can manage threads.
.. versionadded:: 2.0
"""
return 1 << 34
def create_public_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create public threads.
.. versionadded:: 2.0
"""
return 1 << 35
def create_private_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create private threads.
.. versionadded:: 2.0
"""
return 1 << 36
def external_stickers(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use stickers from other guilds.
.. versionadded:: 2.0
"""
return 1 << 37
def use_external_stickers(self) -> int:
""":class:`bool`: An alias for :attr:`external_stickers`.
.. versionadded:: 2.0
"""
return 1 << 37
def send_messages_in_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send messages in threads.
This falls under ``Send Messages in Posts`` on the UI specifically for Forum channels.
.. versionadded:: 2.0
"""
return 1 << 38
def start_embedded_activities(self) -> int:
""":class:`bool`: Returns ``True`` if a user can launch activities in a voice channel.
.. versionadded:: 2.0
"""
return 1 << 39
def moderate_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can moderate members (add timeouts).
Referred to as ``Timeout Members`` in the discord client.
.. versionadded:: 2.0
"""
return 1 << 40
MISSING: Any = _MissingSentinel()
The provided code snippet includes necessary dependencies for implementing the `slash_command` function. Write a Python function `def slash_command( name: Optional[str] = None, description: Optional[str] = None, *, name_localizations: Optional[Dict[Union[Locale, str], str]] = None, description_localizations: Optional[Dict[Union[Locale, str], str]] = None, guild_ids: Optional[Iterable[int]] = MISSING, dm_permission: Optional[bool] = None, default_member_permissions: Optional[Union[Permissions, int]] = None, nsfw: bool = False, force_global: bool = False, )` to solve the following problem:
Creates a Slash application command from the decorated function. Used inside :class:`ClientCog`'s or something that subclasses it. Parameters ---------- name: :class:`str` Name of the command that users will see. If not set, it defaults to the name of the callback. description: :class:`str` Description of the command that users will see. If not specified, the docstring will be used. If no docstring is found for the command callback, it defaults to "No description provided". name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`] Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the value. description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`] Description(s) of the subcommand for users of specific locales. The locale code should be the key, with the localized description as the value. guild_ids: Optional[Iterable[:class:`int`]] IDs of :class:`Guild`'s to add this command to. If not passed and :attr:`Client.default_guild_ids` is set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command. dm_permission: :class:`bool` If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being usable in DMs. Only for global commands, but will not error on guild. default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]] Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements. nsfw: :class:`bool` Whether the command can only be used in age-restricted channels. Defaults to ``False``. .. note:: Due to a discord limitation, this can only be set for the parent command in case of a subcommand. .. versionadded:: 2.4 force_global: :class:`bool` If True, will force this command to register as a global command, even if ``guild_ids`` is set. Will still register to guilds. Has no effect if ``guild_ids`` are never set or added to.
Here is the function:
def slash_command(
name: Optional[str] = None,
description: Optional[str] = None,
*,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
description_localizations: Optional[Dict[Union[Locale, str], str]] = None,
guild_ids: Optional[Iterable[int]] = MISSING,
dm_permission: Optional[bool] = None,
default_member_permissions: Optional[Union[Permissions, int]] = None,
nsfw: bool = False,
force_global: bool = False,
):
"""Creates a Slash application command from the decorated function.
Used inside :class:`ClientCog`'s or something that subclasses it.
Parameters
----------
name: :class:`str`
Name of the command that users will see. If not set, it defaults to the name of the callback.
description: :class:`str`
Description of the command that users will see. If not specified, the docstring will be used.
If no docstring is found for the command callback, it defaults to "No description provided".
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the command for users of specific locales. The locale code should be the key, with the localized
name as the value.
description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Description(s) of the subcommand for users of specific locales. The locale code should be the key, with the
localized description as the value.
guild_ids: Optional[Iterable[:class:`int`]]
IDs of :class:`Guild`'s to add this command to. If not passed and :attr:`Client.default_guild_ids` is
set, then those default guild ids will be used instead. If both of those are unset, then the command will
be a global command.
dm_permission: :class:`bool`
If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being
usable in DMs. Only for global commands, but will not error on guild.
default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]]
Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for
example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by
default. Server owners CAN override the permission requirements.
nsfw: :class:`bool`
Whether the command can only be used in age-restricted channels. Defaults to ``False``.
.. note::
Due to a discord limitation, this can only be set for the parent command in case of a subcommand.
.. versionadded:: 2.4
force_global: :class:`bool`
If True, will force this command to register as a global command, even if ``guild_ids`` is set. Will still
register to guilds. Has no effect if ``guild_ids`` are never set or added to.
"""
def decorator(func: Callable) -> SlashApplicationCommand:
if isinstance(func, BaseApplicationCommand):
raise TypeError("Callback is already an application command.")
return SlashApplicationCommand(
callback=func,
name=name,
name_localizations=name_localizations,
description=description,
description_localizations=description_localizations,
guild_ids=guild_ids,
dm_permission=dm_permission,
default_member_permissions=default_member_permissions,
nsfw=nsfw,
force_global=force_global,
)
return decorator | Creates a Slash application command from the decorated function. Used inside :class:`ClientCog`'s or something that subclasses it. Parameters ---------- name: :class:`str` Name of the command that users will see. If not set, it defaults to the name of the callback. description: :class:`str` Description of the command that users will see. If not specified, the docstring will be used. If no docstring is found for the command callback, it defaults to "No description provided". name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`] Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the value. description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`] Description(s) of the subcommand for users of specific locales. The locale code should be the key, with the localized description as the value. guild_ids: Optional[Iterable[:class:`int`]] IDs of :class:`Guild`'s to add this command to. If not passed and :attr:`Client.default_guild_ids` is set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command. dm_permission: :class:`bool` If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being usable in DMs. Only for global commands, but will not error on guild. default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]] Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements. nsfw: :class:`bool` Whether the command can only be used in age-restricted channels. Defaults to ``False``. .. note:: Due to a discord limitation, this can only be set for the parent command in case of a subcommand. .. versionadded:: 2.4 force_global: :class:`bool` If True, will force this command to register as a global command, even if ``guild_ids`` is set. Will still register to guilds. Has no effect if ``guild_ids`` are never set or added to. |
160,985 | from __future__ import annotations
import asyncio
import contextlib
import logging
import sys
import warnings
from inspect import Parameter, signature
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Coroutine,
Dict,
Iterable,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
import typing_extensions
from typing_extensions import Annotated
from .abc import GuildChannel
from .channel import (
CategoryChannel,
DMChannel,
ForumChannel,
GroupChannel,
StageChannel,
TextChannel,
VoiceChannel,
)
from .enums import ApplicationCommandOptionType, ApplicationCommandType, ChannelType, Locale
from .errors import (
ApplicationCheckFailure,
ApplicationCommandOptionMissing,
ApplicationError,
ApplicationInvokeError,
)
from .guild import Guild
from .interactions import Interaction
from .member import Member
from .message import Attachment, Message
from .object import Object
from .permissions import Permissions
from .role import Role
from .threads import Thread
from .types.interactions import ApplicationCommandInteractionData
from .user import User
from .utils import MISSING, find, maybe_coroutine, parse_docstring
class BaseApplicationCommand(CallbackMixin, CallbackWrapperMixin):
"""Base class for all application commands.
Attributes
----------
checks: List[Union[Callable[[:class:`ClientCog`, :class:`Interaction`], MaybeCoro[:class:`bool`]], Callable[[:class:`Interaction`], MaybeCoro[:class:`bool`]]]]
A list of predicates that verifies if the command could be executed
with the given :class:`Interaction` as the sole parameter. If an exception
is necessary to be thrown to signal failure, then one inherited from
:exc:`.ApplicationError` should be used. Note that if the checks fail then
:exc:`.ApplicationCheckFailure` exception is raised to the :func:`.on_application_command_error`
event.
"""
def __init__(
self,
name: Optional[str] = None,
description: Optional[str] = None,
*,
cmd_type: ApplicationCommandType,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
description_localizations: Optional[Dict[Union[Locale, str], str]] = None,
callback: Optional[Callable] = None,
guild_ids: Optional[Iterable[int]] = MISSING,
dm_permission: Optional[bool] = None,
default_member_permissions: Optional[Union[Permissions, int]] = None,
nsfw: bool = False,
parent_cog: Optional[ClientCog] = None,
force_global: bool = False,
) -> None:
"""Base application command class that all specific application command classes should subclass. All common
behavior should be here, with subclasses either adding on or overriding specific aspects of this class.
Parameters
----------
cmd_type: :class:`ApplicationCommandType`
Type of application command. This should be set by subclasses.
name: :class:`str`
Name of the command.
description: :class:`str`
Description of the command.
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the command for users of specific locales. The locale code should be the key, with the localized
name as the value.
description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Description(s) of the command for users of specific locales. The locale code should be the key, with the
localized description as the value.
callback: :data:`~typing.Callable`
Callback to make the application command from, and to run when the application command is called.
guild_ids: Iterable[:class:`int`]
An iterable list/set/whatever of guild ID's that the application command should register to.
If not passed and :attr:`Client.default_guild_ids` is set, then those default guild ids will
be used instead. If both of those are unset, then the command will be a global command.
dm_permission: :class:`bool`
If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being
usable in DMs. Only for global commands, but will not error on guild.
default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]]
Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for
example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by
default. Server owners CAN override the permission requirements.
nsfw: :class:`bool`
Whether the command can only be used in age-restricted channels. Defaults to ``False``.
.. versionadded:: 2.4
parent_cog: Optional[:class:`ClientCog`]
``ClientCog`` to forward to the callback as the ``self`` argument.
force_global: :class:`bool`
If this command should be registered as a global command, ALONG WITH all guild IDs set.
"""
CallbackWrapperMixin.__init__(self, callback)
CallbackMixin.__init__(self, callback=callback, parent_cog=parent_cog)
self._state: Optional[ConnectionState] = None
self.type = cmd_type or ApplicationCommandType(1)
self.name: Optional[str] = name
self.name_localizations: Optional[Dict[Union[str, Locale], str]] = name_localizations
self._description: Optional[str] = description
self.description_localizations: Optional[
Dict[Union[str, Locale], str]
] = description_localizations
self.guild_ids_to_rollout: Set[int] = set(guild_ids) if guild_ids else set()
self.use_default_guild_ids: bool = guild_ids is MISSING and not force_global
self.dm_permission: Optional[bool] = dm_permission
self.default_member_permissions: Optional[
Union[Permissions, int]
] = default_member_permissions
self.nsfw: bool = nsfw
self.force_global: bool = force_global
self.command_ids: Dict[Optional[int], int] = {}
"""
Dict[Optional[:class:`int`], :class:`int`]:
Command IDs that this application command currently has. Schema: {Guild ID (None for global): command ID}
"""
self.options: Dict[str, ApplicationCommandOption] = {}
# Simple-ish getter + setter methods.
def required_permissions(self) -> Dict[str, bool]:
"""Returns the permissions required to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_permissions", {})
def required_bot_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.bot_has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_bot_permissions", {})
def required_guild_permissions(self) -> Dict[str, bool]:
"""Returns the guild permissions needed to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_guild_permissions", {})
def required_bot_guild_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to have in this guild in order to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.bot_has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_bot_guild_permissions", {})
def qualified_name(self) -> str:
""":class:`str`: Retrieves the fully qualified command name.
.. versionadded:: 2.1
"""
return str(self.name)
def description(self) -> str:
"""The description the command should have in Discord. Should be 1-100 characters long."""
return self._description or DEFAULT_SLASH_DESCRIPTION
def description(self, new_description: str) -> None:
self._description = new_description
def is_guild(self) -> bool:
""":class:`bool`: Returns ``True`` if this command is or should be registered to any guilds."""
guild_only_ids = set(self.command_ids.keys())
guild_only_ids.discard(None)
return bool(self.guild_ids_to_rollout or guild_only_ids)
def guild_ids(self) -> Set[int]:
"""Returns a :class:`set` containing all guild ID's this command is registered to."""
# TODO: Is this worthwhile?
guild_only_ids = set(self.command_ids.keys())
guild_only_ids.discard(None)
# ignore explanation: Mypy says that guild_only_ids can contain None due to self.command_ids.keys() having
# None being typehinted, but we remove None before returning it.
return guild_only_ids # type: ignore
def add_guild_rollout(self, guild: Union[int, Guild]) -> None:
"""Adds a Guild to the command to be rolled out to when the rollout is run.
Parameters
----------
guild: Union[:class:`int`, :class:`Guild`]
Guild or Guild ID to add this command to roll out to.
"""
self.guild_ids_to_rollout.add(guild.id if isinstance(guild, Guild) else guild)
def is_global(self) -> bool:
""":class:`bool`: Returns ``True`` if this command is or should be a global command."""
return self.force_global or not self.is_guild or None in self.command_ids
def get_signature(
self, guild_id: Optional[int] = None
) -> Tuple[Optional[str], int, Optional[int]]:
"""Returns a command signature with the given guild ID.
Parameters
----------
guild_id: Optional[:class:`None`]
Guild ID to make the signature for. If set to ``None``, it acts as a global command signature.
Returns
-------
Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]
A tuple that acts as a signature made up of the name, type, and guild ID.
"""
# noinspection PyUnresolvedReferences
return self.name, self.type.value, guild_id
def get_rollout_signatures(self) -> Set[Tuple[str, int, Optional[int]]]:
"""Returns all signatures that this command wants to roll out to.
Command signatures are made up of the command name, command type, and Guild ID (``None`` for global).
Returns
-------
Set[Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]]
A set of tuples that act as signatures.
"""
ret = set()
if self.is_global:
ret.add(self.get_signature(None))
for guild_id in self.guild_ids_to_rollout:
ret.add(self.get_signature(guild_id))
return ret
def get_signatures(self) -> Set[Tuple[str, int, Optional[int]]]:
"""Returns all the signatures that this command has.
Command signatures are made up of the command name, command type, and Guild ID (``None`` for global).
Returns
-------
Set[Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]]
A set of tuples that act as signatures.
"""
ret = set()
if self.is_global:
ret.add(self.get_signature(None))
if self.is_guild:
for guild_id in self.guild_ids:
ret.add(self.get_signature(guild_id))
return ret
def get_name_localization_payload(self) -> Optional[Dict[str, str]]:
if self.name_localizations:
ret = {}
for locale, name in self.name_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = name
else:
ret[locale] = name
return ret
return None
def get_description_localization_payload(self) -> Optional[dict]:
if self.description_localizations:
ret = {}
for locale, description in self.description_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = description
else:
ret[locale] = description
return ret
return None
def get_default_member_permissions_value(self) -> Optional[int]:
if (
isinstance(self.default_member_permissions, int)
or self.default_member_permissions is None
):
return self.default_member_permissions
return self.default_member_permissions.value
def get_payload(self, guild_id: Optional[int]) -> dict:
"""Makes an Application Command payload for this command to upsert to Discord with the given Guild ID.
Parameters
----------
guild_id: Optional[:class:`int`]
Guild ID that this payload is for. If set to ``None``, it will be a global command payload instead.
Returns
-------
:class:`dict`
Dictionary payload to upsert to Discord.
"""
# Below is to make PyCharm stop complaining that self.type.value isn't valid.
# noinspection PyUnresolvedReferences
ret = {
"type": self.type.value,
"name": str(
self.name
), # Might as well stringify the name, will come in handy if people try using numbers.
"description": str(self.description), # Might as well do the same with the description.
"name_localizations": self.get_name_localization_payload(),
"description_localizations": self.get_description_localization_payload(),
}
if self.default_member_permissions is not None:
# While Discord accepts it as an int, they will respond back with the permissions value as a string because
# the permissions bitfield can get too big for them. Stringify it for easy payload-comparison.
ret["default_member_permissions"] = str(self.get_default_member_permissions_value())
if guild_id: # Guild-command specific payload options.
ret["guild_id"] = guild_id
# Global command specific payload options.
elif self.dm_permission is not None:
ret["dm_permission"] = self.dm_permission
else:
# Discord seems to send back the DM permission as True regardless if we sent it or not, so we send as
# the default (True) to ensure payload parity for comparisons.
ret["dm_permission"] = True
ret["nsfw"] = self.nsfw
return ret
def parse_discord_response(
self,
state: ConnectionState,
data: Union[ApplicationCommandInteractionData, ApplicationCommandPayload],
) -> None:
"""Parses the application command creation/update response from Discord.
Parameters
----------
state: :class:`ConnectionState`
Connection state to use internally in the command.
data: Union[:class:`ApplicationCommandInteractionData`, :class:`ApplicationCommand`]
Raw dictionary data from Discord.
"""
self._state = state
command_id = int(data["id"])
if guild_id := data.get("guild_id", None):
guild_id = int(guild_id)
self.command_ids[guild_id] = command_id
self.guild_ids_to_rollout.add(guild_id)
else:
self.command_ids[None] = command_id
def is_payload_valid(
self, raw_payload: ApplicationCommandPayload, guild_id: Optional[int] = None
) -> bool:
"""Checks if the given raw application command interaction payload from Discord is possibly valid for
this command.
Note that while this may return ``True`` for a given payload, that doesn't mean that the payload is fully
correct for this command. Discord doesn't send data for parameters that are optional and aren't supplied by
the user.
Parameters
----------
raw_payload: :class:`dict`
Application command interaction payload from Discord.
guild_id: Optional[:class:`int`]
Guild ID that the payload is from. If it's from a global command, this should be ``None``
Returns
-------
:class:`bool`
``True`` if the given payload is possibly valid for this command. ``False`` otherwise.
"""
cmd_payload = self.get_payload(guild_id)
if cmd_payload.get("guild_id", 0) != int(raw_payload.get("guild_id", 0)):
_log.debug("Guild ID doesn't match raw payload, not valid payload.")
return False
if not check_dictionary_values(
cmd_payload,
raw_payload, # type: ignore # specificity of typeddicts doesnt matter in validation
"default_member_permissions",
"description",
"type",
"name",
"name_localizations",
"description_localizations",
"dm_permission",
"nsfw",
):
_log.debug("Failed check dictionary values, not valid payload.")
return False
if len(cmd_payload.get("options", [])) != len(raw_payload.get("options", [])):
_log.debug("Option amount between commands not equal, not valid payload.")
return False
for cmd_option in cmd_payload.get("options", []):
# I absolutely do not trust Discord or us ordering things nicely, so check through both.
found_correct_value = False
for raw_option in raw_payload.get("options", []):
if cmd_option["name"] == raw_option["name"]:
found_correct_value = True
# At this time, ApplicationCommand options are identical between locally-generated payloads and
# payloads from Discord. If that were to change, switch from a recursive setup and manually
# check_dictionary_values.
if not deep_dictionary_check(cmd_option, raw_option): # type: ignore
# its a dict check so typeddicts do not matter
_log.debug("Options failed deep dictionary checks, not valid payload.")
return False
break
if not found_correct_value:
_log.debug("Discord is missing an option we have, not valid payload.")
return False
return True
def is_interaction_valid(self, interaction: Interaction) -> bool:
"""Checks if the interaction given is possibly valid for this command.
If the command has more parameters (especially optionals) than the interaction coming in, this may cause a
desync between your bot and Discord.
Parameters
----------
interaction: :class:`Interaction`
Interaction to validate.
Returns
-------
:class:`bool`
``True`` If the interaction could possibly be for this command, ``False`` otherwise.
"""
data = interaction.data
if data is None:
raise ValueError("Discord did not provide us with interaction data")
our_payload = self.get_payload(data.get("guild_id", None))
def _recursive_subcommand_check(inter_pos: dict, cmd_pos: dict) -> bool:
"""A small recursive wrapper that checks for subcommand(s) (group(s)).
Parameters
----------
inter_pos: :class:`dict`
Current command position from the payload in the interaction.
cmd_pos: :class:`dict`
Current command position from the payload for the local command.
Returns
-------
:class:`bool`
``True`` if the payloads match, ``False`` otherwise.
"""
inter_options = inter_pos.get("options")
cmd_options = cmd_pos.get("options", {})
if inter_options is None:
raise ValueError("Interaction options was not provided")
our_options = {opt["name"]: opt for opt in cmd_options}
if (
len(inter_options) == 1
and ( # If the length is only 1, it might be a subcommand (group).
inter_options[0]["type"]
in (
ApplicationCommandOptionType.sub_command.value,
ApplicationCommandOptionType.sub_command_group.value,
)
)
and ( # This checks if it's a subcommand (group).
found_opt := our_options.get(
inter_options[0]["name"]
) # This checks if the name matches an option.
)
and inter_options[0]["type"] == found_opt["type"]
): # And this makes sure both are the same type.
return _recursive_subcommand_check(
inter_options[0], found_opt
) # If all of the above pass, recurse.
return _option_check(inter_options, cmd_options)
def _option_check(inter_options: dict, cmd_options: dict) -> bool:
"""Checks if the two given command payloads have matching options.
Parameters
----------
inter_options: :class:`dict`
Command option data from the interaction.
cmd_options: :class:`dict`
Command option data from the local command.
Returns
-------
:class:`bool`
``True`` if the options match, ``False`` otherwise.
"""
all_our_options = {}
required_options = {}
for our_opt in cmd_options:
all_our_options[our_opt["name"]] = our_opt
if our_opt.get("required"):
required_options[our_opt["name"]] = our_opt
all_inter_options = {inter_opt["name"]: inter_opt for inter_opt in inter_options}
if len(all_our_options) >= len(all_inter_options):
# If we have more options (including options) than the interaction, we are good to proceed.
all_our_options_copy = all_our_options.copy()
all_inter_options_copy = all_inter_options.copy()
# Begin checking required options.
for our_opt_name, our_opt in required_options.items():
if inter_opt := all_inter_options.get(our_opt_name):
if (
inter_opt["name"] == our_opt["name"]
and inter_opt["type"] == our_opt["type"]
):
all_our_options_copy.pop(our_opt_name)
all_inter_options_copy.pop(our_opt_name)
else:
_log.debug(
"%s Required option don't match name and/or type.", self.error_name
)
return False # Options don't match name and/or type.
else:
_log.debug("%s Inter missing required option.", self.error_name)
return False # Required option wasn't found.
# Begin checking optional arguments.
for (
inter_opt_name,
inter_opt,
) in all_inter_options_copy.items(): # Should only contain optionals now.
if our_opt := all_our_options_copy.get(inter_opt_name):
if not (
inter_opt["name"] == our_opt["name"]
and inter_opt["type"] == our_opt["type"]
):
_log.debug(
"%s Optional option don't match name and/or type.", self.error_name
)
return False # Options don't match name and/or type.
else:
_log.debug("%s Inter has option that we don't.", self.error_name)
return False # They have an option name that we don't.
else:
_log.debug(
"%s We have less options than them: %s vs %s",
self.error_name,
all_our_options,
all_inter_options,
)
return False # Interaction has more options than we do.
return True # No checks failed.
# caring about typeddict specificity will cause issues down the line
if not check_dictionary_values(our_payload, data, "name", "guild_id", "type"): # type: ignore
_log.debug("%s Failed basic dictionary check.", self.error_name)
return False
data_options = data.get("options")
payload_options = our_payload.get("options")
if data_options and payload_options:
return _recursive_subcommand_check(data, our_payload) # type: ignore
if data_options is None and payload_options is None:
return True # User and Message commands don't have options.
_log.debug(
"%s Mismatch between data and payload options: %s vs %s",
self.error_name,
data_options,
payload_options,
)
# There is a mismatch between the two, fail it.
return False
def from_callback(
self,
callback: Optional[Callable] = None,
option_class: Optional[Type[BaseCommandOption]] = BaseCommandOption,
) -> None:
super().from_callback(callback=callback, option_class=option_class)
async def call_from_interaction(self, interaction: Interaction) -> None:
"""|coro|
Calls the callback via the given :class:`Interaction`, relying on the locally
stored :class:`ConnectionState` object.
Parameters
----------
interaction: :class:`Interaction`
Interaction corresponding to the use of the command.
"""
await self.call(self._state, interaction) # type: ignore
async def call(self, state: ConnectionState, interaction: Interaction) -> None:
"""|coro|
Calls the callback via the given :class:`Interaction`, using the given :class:`ConnectionState` to get resolved
objects if needed and available.
Parameters
----------
state: :class:`ConnectionState`
State object to get resolved objects from.
interaction: :class:`Interaction`
Interaction corresponding to the use of the command.
"""
raise NotImplementedError
def check_against_raw_payload(
self, raw_payload: ApplicationCommandPayload, guild_id: Optional[int] = None
) -> bool:
warnings.warn(
".check_against_raw_payload() is deprecated, please use .is_payload_valid instead.",
stacklevel=2,
category=FutureWarning,
)
return self.is_payload_valid(raw_payload, guild_id)
def get_guild_payload(self, guild_id: int):
warnings.warn(
".get_guild_payload is deprecated, use .get_payload(guild_id) instead.",
stacklevel=2,
category=FutureWarning,
)
return self.get_payload(guild_id)
def global_payload(self) -> dict:
warnings.warn(
".global_payload is deprecated, use .get_payload(None) instead.",
stacklevel=2,
category=FutureWarning,
)
return self.get_payload(None)
class MessageApplicationCommand(BaseApplicationCommand):
"""Class representing a message context menu command."""
def __init__(
self,
name: Optional[str] = None,
*,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
callback: Optional[Callable] = None,
guild_ids: Optional[Iterable[int]] = None,
dm_permission: Optional[bool] = None,
default_member_permissions: Optional[Union[Permissions, int]] = None,
nsfw: bool = False,
parent_cog: Optional[ClientCog] = None,
force_global: bool = False,
) -> None:
"""Represents a Message Application Command that will give the message to the given callback, able to be
registered to multiple guilds or globally.
Parameters
----------
name: :class:`str`
Name of the command. Can be uppercase with spaces.
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the subcommand for users of specific locales. The locale code should be the key, with the
localized name as the value.
callback: :data:`~typing.Callable`
Callback to run with the application command is called.
guild_ids: Iterable[:class:`int`]
An iterable list of guild ID's that the application command should register to.
dm_permission: :class:`bool`
If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being
usable in DMs. Only for global commands, but will not error on guild.
default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]]
Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for
example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by
default. Server owners CAN override the permission requirements.
nsfw: :class:`bool`
Whether the command can only be used in age-restricted channels. Defaults to ``False``.
.. versionadded:: 2.4
parent_cog: Optional[:class:`ClientCog`]
``ClientCog`` to forward to the callback as the ``self`` argument.
force_global: :class:`bool`
If this command should be registered as a global command, ALONG WITH all guild IDs set.
"""
super().__init__(
name=name,
name_localizations=name_localizations,
description="",
callback=callback,
cmd_type=ApplicationCommandType.message,
guild_ids=guild_ids,
dm_permission=dm_permission,
default_member_permissions=default_member_permissions,
nsfw=nsfw,
parent_cog=parent_cog,
force_global=force_global,
)
def description(self) -> str:
return ""
def description(self, new_desc: str):
raise ValueError("MessageApplicationCommands cannot have a description set.")
async def call(self, state: ConnectionState, interaction: Interaction) -> None:
await self.invoke_callback_with_hooks(
state, interaction, args=(get_messages_from_interaction(state, interaction)[0],)
)
def from_callback(
self,
callback: Optional[Callable] = None,
option_class: Optional[Type[BaseCommandOption]] = None,
) -> None:
super().from_callback(callback, option_class=option_class)
CallbackWrapperMixin.modify(self)
class Locale(StrEnum):
da = "da"
"""Danish | Dansk"""
de = "de"
"""German | Deutsch"""
en_GB = "en-GB"
"""English, UK | English, UK"""
en_US = "en-US"
"""English, US | English, US"""
es_ES = "es-ES"
"""Spanish | Español"""
fr = "fr"
"""French | Français"""
hr = "hr"
"""Croatian | Hrvatski"""
id = "id"
"""Indonesian | Bahasa Indonesia
.. versionadded:: 2.4
"""
it = "it"
"""Italian | Italiano"""
lt = "lt"
"""Lithuanian | Lietuviškai"""
hu = "hu"
"""Hungarian | Magyar"""
nl = "nl"
"""Dutch | Nederlands"""
no = "no"
"""Norwegian | Norsk"""
pl = "pl"
"""Polish | Polski"""
pt_BR = "pt-BR"
"""Portuguese, Brazilian | Português do Brasil"""
ro = "ro"
"""Romanian, Romania | Română"""
fi = "fi"
"""Finnish | Suomi"""
sv_SE = "sv-SE"
"""Swedish | Svenska"""
vi = "vi"
"""Vietnamese | Tiếng Việt"""
tr = "tr"
"""Turkish | Türkçe"""
cs = "cs"
"""Czech | Čeština"""
el = "el"
"""Greek | Ελληνικά"""
bg = "bg"
"""Bulgarian | български"""
ru = "ru"
"""Russian | Pусский""" # noqa: RUF001
uk = "uk"
"""Ukrainian | Українська"""
hi = "hi"
"""Hindi | हिन्दी"""
th = "th"
"""Thai | ไทย"""
zh_CN = "zh-CN"
"""Chinese, China | 中文"""
ja = "ja"
"""Japanese | 日本語"""
zh_TW = "zh-TW"
"""Chinese, Taiwan | 繁體中文"""
ko = "ko"
"""Korean | 한국어"""
class Permissions(BaseFlags):
"""Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual
bits using the properties as if they were regular bools. This allows
you to edit permissions.
.. versionchanged:: 1.3
You can now use keyword arguments to initialize :class:`Permissions`
similar to :meth:`update`.
.. container:: operations
.. describe:: x == y
Checks if two permissions are equal.
.. describe:: x != y
Checks if two permissions are not equal.
.. describe:: x <= y
Checks if a permission is a subset of another permission.
.. describe:: x >= y
Checks if a permission is a superset of another permission.
.. describe:: x < y
Checks if a permission is a strict subset of another permission.
.. describe:: x > y
Checks if a permission is a strict superset of another permission.
.. describe:: hash(x)
Return the permission's hash.
.. describe:: iter(x)
Returns an iterator of ``(perm, value)`` pairs. This allows it
to be, for example, constructed as a dict or a list of pairs.
Note that aliases are not shown.
Attributes
----------
value: :class:`int`
The raw value. This value is a bit array field of a 53-bit integer
representing the currently available permissions. You should query
permissions via the properties rather than using this raw value.
"""
__slots__ = ()
def __init__(self, permissions: int = 0, **kwargs: bool) -> None:
if not isinstance(permissions, int):
raise TypeError(
f"Expected int parameter, received {permissions.__class__.__name__} instead."
)
self.value = permissions
for key, value in kwargs.items():
if key not in self.VALID_FLAGS:
raise TypeError(f"{key!r} is not a valid permission name.")
setattr(self, key, value)
def is_subset(self, other: Permissions) -> bool:
"""Returns ``True`` if self has the same or fewer permissions as other."""
if isinstance(other, Permissions):
return (self.value & other.value) == self.value
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}")
def is_superset(self, other: Permissions) -> bool:
"""Returns ``True`` if self has the same or more permissions as other."""
if isinstance(other, Permissions):
return (self.value | other.value) == self.value
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}")
def is_strict_subset(self, other: Permissions) -> bool:
"""Returns ``True`` if the permissions on other are a strict subset of those on self."""
return self.is_subset(other) and self != other
def is_strict_superset(self, other: Permissions) -> bool:
"""Returns ``True`` if the permissions on other are a strict superset of those on self."""
return self.is_superset(other) and self != other
__le__ = is_subset
__ge__ = is_superset
__lt__ = is_strict_subset
__gt__ = is_strict_superset
def none(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
permissions set to ``False``."""
return cls(0)
def all(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
permissions set to ``True``.
"""
return cls(-1)
def all_channel(cls) -> Self:
"""A :class:`Permissions` with all channel-specific permissions set to
``True`` and the guild-specific ones set to ``False``. The guild-specific
permissions are currently:
- :attr:`manage_emojis`
- :attr:`view_audit_log`
- :attr:`view_guild_insights`
- :attr:`manage_guild`
- :attr:`change_nickname`
- :attr:`manage_nicknames`
- :attr:`kick_members`
- :attr:`ban_members`
- :attr:`administrator`
.. versionchanged:: 1.7
Added :attr:`stream`, :attr:`priority_speaker` and :attr:`use_slash_commands` permissions.
.. versionchanged:: 2.0
Added :attr:`create_public_threads`, :attr:`create_private_threads`, :attr:`manage_threads`,
:attr:`use_external_stickers`, :attr:`send_messages_in_threads` and
:attr:`request_to_speak` permissions.
"""
return cls(0b111110110110011111101111111111101010001)
def general(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"General" permissions from the official Discord UI set to ``True``.
.. versionchanged:: 1.7
Permission :attr:`read_messages` is now included in the general permissions, but
permissions :attr:`administrator`, :attr:`create_instant_invite`, :attr:`kick_members`,
:attr:`ban_members`, :attr:`change_nickname` and :attr:`manage_nicknames` are
no longer part of the general permissions.
"""
return cls(0b01110000000010000000010010110000)
def membership(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Membership" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(0b00001100000000000000000000000111)
def text(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Text" permissions from the official Discord UI set to ``True``.
.. versionchanged:: 1.7
Permission :attr:`read_messages` is no longer part of the text permissions.
Added :attr:`use_slash_commands` permission.
.. versionchanged:: 2.0
Added :attr:`create_public_threads`, :attr:`create_private_threads`, :attr:`manage_threads`,
:attr:`send_messages_in_threads` and :attr:`use_external_stickers` permissions.
"""
return cls(0b111110010000000000001111111100001000000)
def voice(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Voice" permissions from the official Discord UI set to ``True``."""
return cls(0b00000011111100000000001100000000)
def stage(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Stage Channel" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(1 << 32)
def stage_moderator(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Stage Moderator" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(0b100000001010000000000000000000000)
def advanced(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Advanced" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(1 << 3)
def update(self, **kwargs: bool) -> None:
r"""Bulk updates this permission object.
Allows you to set multiple attributes by using keyword
arguments. The names must be equivalent to the properties
listed. Extraneous key/value pairs will be silently ignored.
Parameters
----------
\*\*kwargs
A list of key/value pairs to bulk update permissions with.
"""
for key, value in kwargs.items():
if key in self.VALID_FLAGS:
setattr(self, key, value)
def handle_overwrite(self, allow: int, deny: int) -> None:
# Basically this is what's happening here.
# We have an original bit array, e.g. 1010
# Then we have another bit array that is 'denied', e.g. 1111
# And then we have the last one which is 'allowed', e.g. 0101
# We want original OP denied to end up resulting in
# whatever is in denied to be set to 0.
# So 1010 OP 1111 -> 0000
# Then we take this value and look at the allowed values.
# And whatever is allowed is set to 1.
# So 0000 OP2 0101 -> 0101
# The OP is base & ~denied.
# The OP2 is base | allowed.
self.value = (self.value & ~deny) | allow
def create_instant_invite(self) -> int:
""":class:`bool`: Returns ``True`` if the user can create instant invites."""
return 1 << 0
def kick_members(self) -> int:
""":class:`bool`: Returns ``True`` if the user can kick users from the guild."""
return 1 << 1
def ban_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can ban users from the guild."""
return 1 << 2
def administrator(self) -> int:
""":class:`bool`: Returns ``True`` if a user is an administrator. This role overrides all other permissions.
This also bypasses all channel-specific overrides.
"""
return 1 << 3
def manage_channels(self) -> int:
""":class:`bool`: Returns ``True`` if a user can edit, delete, or create channels in the guild.
This also corresponds to the "Manage Channel" channel-specific override."""
return 1 << 4
def manage_guild(self) -> int:
""":class:`bool`: Returns ``True`` if a user can edit guild properties."""
return 1 << 5
def add_reactions(self) -> int:
""":class:`bool`: Returns ``True`` if a user can add reactions to messages."""
return 1 << 6
def view_audit_log(self) -> int:
""":class:`bool`: Returns ``True`` if a user can view the guild's audit log."""
return 1 << 7
def priority_speaker(self) -> int:
""":class:`bool`: Returns ``True`` if a user can be more easily heard while talking."""
return 1 << 8
def stream(self) -> int:
""":class:`bool`: Returns ``True`` if a user can stream in a voice channel."""
return 1 << 9
def read_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can read messages from all or specific text channels."""
return 1 << 10
def view_channel(self) -> int:
""":class:`bool`: An alias for :attr:`read_messages`.
.. versionadded:: 1.3
"""
return 1 << 10
def send_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send messages from all or specific text channels.
This falls under ``Create Posts`` on the UI specifically for Forum Channels.
"""
return 1 << 11
def send_tts_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send TTS messages from all or specific text channels."""
return 1 << 12
def manage_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can delete or pin messages in a text channel.
.. note::
Note that there are currently no ways to edit other people's messages.
"""
return 1 << 13
def embed_links(self) -> int:
""":class:`bool`: Returns ``True`` if a user's messages will automatically be embedded by Discord."""
return 1 << 14
def attach_files(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send files in their messages."""
return 1 << 15
def read_message_history(self) -> int:
""":class:`bool`: Returns ``True`` if a user can read a text channel's previous messages."""
return 1 << 16
def mention_everyone(self) -> int:
""":class:`bool`: Returns ``True`` if a user's @everyone or @here will mention everyone in the text channel."""
return 1 << 17
def external_emojis(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use emojis from other guilds."""
return 1 << 18
def use_external_emojis(self) -> int:
""":class:`bool`: An alias for :attr:`external_emojis`.
.. versionadded:: 1.3
"""
return 1 << 18
def view_guild_insights(self) -> int:
""":class:`bool`: Returns ``True`` if a user can view the guild's insights.
.. versionadded:: 1.3
"""
return 1 << 19
def connect(self) -> int:
""":class:`bool`: Returns ``True`` if a user can connect to a voice channel."""
return 1 << 20
def speak(self) -> int:
""":class:`bool`: Returns ``True`` if a user can speak in a voice channel."""
return 1 << 21
def mute_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can mute other users."""
return 1 << 22
def deafen_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can deafen other users."""
return 1 << 23
def move_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can move users between other voice channels."""
return 1 << 24
def use_voice_activation(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use voice activation in voice channels."""
return 1 << 25
def change_nickname(self) -> int:
""":class:`bool`: Returns ``True`` if a user can change their nickname in the guild."""
return 1 << 26
def manage_nicknames(self) -> int:
""":class:`bool`: Returns ``True`` if a user can change other user's nickname in the guild."""
return 1 << 27
def manage_roles(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create or edit roles less than their role's position.
This also corresponds to the "Manage Permissions" channel-specific override.
"""
return 1 << 28
def manage_permissions(self) -> int:
""":class:`bool`: An alias for :attr:`manage_roles`.
.. versionadded:: 1.3
"""
return 1 << 28
def manage_webhooks(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create, edit, or delete webhooks."""
return 1 << 29
def manage_emojis(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create, edit, or delete emojis."""
return 1 << 30
def manage_emojis_and_stickers(self) -> int:
""":class:`bool`: An alias for :attr:`manage_emojis`.
.. versionadded:: 2.0
"""
return 1 << 30
def use_slash_commands(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use slash commands.
.. versionadded:: 1.7
"""
return 1 << 31
def request_to_speak(self) -> int:
""":class:`bool`: Returns ``True`` if a user can request to speak in a stage channel.
.. versionadded:: 1.7
"""
return 1 << 32
def manage_events(self) -> int:
""":class:`bool`: Returns ``True`` if a user can manage guild events.
.. versionadded:: 2.0
"""
return 1 << 33
def manage_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can manage threads.
.. versionadded:: 2.0
"""
return 1 << 34
def create_public_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create public threads.
.. versionadded:: 2.0
"""
return 1 << 35
def create_private_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create private threads.
.. versionadded:: 2.0
"""
return 1 << 36
def external_stickers(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use stickers from other guilds.
.. versionadded:: 2.0
"""
return 1 << 37
def use_external_stickers(self) -> int:
""":class:`bool`: An alias for :attr:`external_stickers`.
.. versionadded:: 2.0
"""
return 1 << 37
def send_messages_in_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send messages in threads.
This falls under ``Send Messages in Posts`` on the UI specifically for Forum channels.
.. versionadded:: 2.0
"""
return 1 << 38
def start_embedded_activities(self) -> int:
""":class:`bool`: Returns ``True`` if a user can launch activities in a voice channel.
.. versionadded:: 2.0
"""
return 1 << 39
def moderate_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can moderate members (add timeouts).
Referred to as ``Timeout Members`` in the discord client.
.. versionadded:: 2.0
"""
return 1 << 40
MISSING: Any = _MissingSentinel()
The provided code snippet includes necessary dependencies for implementing the `message_command` function. Write a Python function `def message_command( name: Optional[str] = None, *, name_localizations: Optional[Dict[Union[Locale, str], str]] = None, guild_ids: Optional[Iterable[int]] = MISSING, dm_permission: Optional[bool] = None, default_member_permissions: Optional[Union[Permissions, int]] = None, nsfw: bool = False, force_global: bool = False, )` to solve the following problem:
Creates a Message context command from the decorated function. Used inside :class:`ClientCog`'s or something that subclasses it. Parameters ---------- name: :class:`str` Name of the command that users will see. If not set, it defaults to the name of the callback. name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`] Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the value guild_ids: Optional[Iterable[:class:`int`]] IDs of :class:`Guild`'s to add this command to. If not passed and :attr:`Client.default_guild_ids` is set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command. dm_permission: :class:`bool` If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being usable in DMs. Only for global commands, but will not error on guild. default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]] Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements. nsfw: :class:`bool` Whether the command can only be used in age-restricted channels. Defaults to ``False``. .. versionadded:: 2.4 force_global: :class:`bool` If True, will force this command to register as a global command, even if ``guild_ids`` is set. Will still register to guilds. Has no effect if ``guild_ids`` are never set or added to.
Here is the function:
def message_command(
name: Optional[str] = None,
*,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
guild_ids: Optional[Iterable[int]] = MISSING,
dm_permission: Optional[bool] = None,
default_member_permissions: Optional[Union[Permissions, int]] = None,
nsfw: bool = False,
force_global: bool = False,
):
"""Creates a Message context command from the decorated function.
Used inside :class:`ClientCog`'s or something that subclasses it.
Parameters
----------
name: :class:`str`
Name of the command that users will see. If not set, it defaults to the name of the callback.
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the command for users of specific locales. The locale code should be the key, with the localized
name as the value
guild_ids: Optional[Iterable[:class:`int`]]
IDs of :class:`Guild`'s to add this command to. If not passed and :attr:`Client.default_guild_ids` is
set, then those default guild ids will be used instead. If both of those are unset, then the command will
be a global command.
dm_permission: :class:`bool`
If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being
usable in DMs. Only for global commands, but will not error on guild.
default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]]
Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for
example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by
default. Server owners CAN override the permission requirements.
nsfw: :class:`bool`
Whether the command can only be used in age-restricted channels. Defaults to ``False``.
.. versionadded:: 2.4
force_global: :class:`bool`
If True, will force this command to register as a global command, even if ``guild_ids`` is set. Will still
register to guilds. Has no effect if ``guild_ids`` are never set or added to.
"""
def decorator(func: Callable) -> MessageApplicationCommand:
if isinstance(func, BaseApplicationCommand):
raise TypeError("Callback is already an application command.")
return MessageApplicationCommand(
callback=func,
name=name,
name_localizations=name_localizations,
guild_ids=guild_ids,
dm_permission=dm_permission,
default_member_permissions=default_member_permissions,
nsfw=nsfw,
force_global=force_global,
)
return decorator | Creates a Message context command from the decorated function. Used inside :class:`ClientCog`'s or something that subclasses it. Parameters ---------- name: :class:`str` Name of the command that users will see. If not set, it defaults to the name of the callback. name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`] Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the value guild_ids: Optional[Iterable[:class:`int`]] IDs of :class:`Guild`'s to add this command to. If not passed and :attr:`Client.default_guild_ids` is set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command. dm_permission: :class:`bool` If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being usable in DMs. Only for global commands, but will not error on guild. default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]] Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements. nsfw: :class:`bool` Whether the command can only be used in age-restricted channels. Defaults to ``False``. .. versionadded:: 2.4 force_global: :class:`bool` If True, will force this command to register as a global command, even if ``guild_ids`` is set. Will still register to guilds. Has no effect if ``guild_ids`` are never set or added to. |
160,986 | from __future__ import annotations
import asyncio
import contextlib
import logging
import sys
import warnings
from inspect import Parameter, signature
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Coroutine,
Dict,
Iterable,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
import typing_extensions
from typing_extensions import Annotated
from .abc import GuildChannel
from .channel import (
CategoryChannel,
DMChannel,
ForumChannel,
GroupChannel,
StageChannel,
TextChannel,
VoiceChannel,
)
from .enums import ApplicationCommandOptionType, ApplicationCommandType, ChannelType, Locale
from .errors import (
ApplicationCheckFailure,
ApplicationCommandOptionMissing,
ApplicationError,
ApplicationInvokeError,
)
from .guild import Guild
from .interactions import Interaction
from .member import Member
from .message import Attachment, Message
from .object import Object
from .permissions import Permissions
from .role import Role
from .threads import Thread
from .types.interactions import ApplicationCommandInteractionData
from .user import User
from .utils import MISSING, find, maybe_coroutine, parse_docstring
class BaseApplicationCommand(CallbackMixin, CallbackWrapperMixin):
"""Base class for all application commands.
Attributes
----------
checks: List[Union[Callable[[:class:`ClientCog`, :class:`Interaction`], MaybeCoro[:class:`bool`]], Callable[[:class:`Interaction`], MaybeCoro[:class:`bool`]]]]
A list of predicates that verifies if the command could be executed
with the given :class:`Interaction` as the sole parameter. If an exception
is necessary to be thrown to signal failure, then one inherited from
:exc:`.ApplicationError` should be used. Note that if the checks fail then
:exc:`.ApplicationCheckFailure` exception is raised to the :func:`.on_application_command_error`
event.
"""
def __init__(
self,
name: Optional[str] = None,
description: Optional[str] = None,
*,
cmd_type: ApplicationCommandType,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
description_localizations: Optional[Dict[Union[Locale, str], str]] = None,
callback: Optional[Callable] = None,
guild_ids: Optional[Iterable[int]] = MISSING,
dm_permission: Optional[bool] = None,
default_member_permissions: Optional[Union[Permissions, int]] = None,
nsfw: bool = False,
parent_cog: Optional[ClientCog] = None,
force_global: bool = False,
) -> None:
"""Base application command class that all specific application command classes should subclass. All common
behavior should be here, with subclasses either adding on or overriding specific aspects of this class.
Parameters
----------
cmd_type: :class:`ApplicationCommandType`
Type of application command. This should be set by subclasses.
name: :class:`str`
Name of the command.
description: :class:`str`
Description of the command.
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the command for users of specific locales. The locale code should be the key, with the localized
name as the value.
description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Description(s) of the command for users of specific locales. The locale code should be the key, with the
localized description as the value.
callback: :data:`~typing.Callable`
Callback to make the application command from, and to run when the application command is called.
guild_ids: Iterable[:class:`int`]
An iterable list/set/whatever of guild ID's that the application command should register to.
If not passed and :attr:`Client.default_guild_ids` is set, then those default guild ids will
be used instead. If both of those are unset, then the command will be a global command.
dm_permission: :class:`bool`
If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being
usable in DMs. Only for global commands, but will not error on guild.
default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]]
Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for
example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by
default. Server owners CAN override the permission requirements.
nsfw: :class:`bool`
Whether the command can only be used in age-restricted channels. Defaults to ``False``.
.. versionadded:: 2.4
parent_cog: Optional[:class:`ClientCog`]
``ClientCog`` to forward to the callback as the ``self`` argument.
force_global: :class:`bool`
If this command should be registered as a global command, ALONG WITH all guild IDs set.
"""
CallbackWrapperMixin.__init__(self, callback)
CallbackMixin.__init__(self, callback=callback, parent_cog=parent_cog)
self._state: Optional[ConnectionState] = None
self.type = cmd_type or ApplicationCommandType(1)
self.name: Optional[str] = name
self.name_localizations: Optional[Dict[Union[str, Locale], str]] = name_localizations
self._description: Optional[str] = description
self.description_localizations: Optional[
Dict[Union[str, Locale], str]
] = description_localizations
self.guild_ids_to_rollout: Set[int] = set(guild_ids) if guild_ids else set()
self.use_default_guild_ids: bool = guild_ids is MISSING and not force_global
self.dm_permission: Optional[bool] = dm_permission
self.default_member_permissions: Optional[
Union[Permissions, int]
] = default_member_permissions
self.nsfw: bool = nsfw
self.force_global: bool = force_global
self.command_ids: Dict[Optional[int], int] = {}
"""
Dict[Optional[:class:`int`], :class:`int`]:
Command IDs that this application command currently has. Schema: {Guild ID (None for global): command ID}
"""
self.options: Dict[str, ApplicationCommandOption] = {}
# Simple-ish getter + setter methods.
def required_permissions(self) -> Dict[str, bool]:
"""Returns the permissions required to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_permissions", {})
def required_bot_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.bot_has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_bot_permissions", {})
def required_guild_permissions(self) -> Dict[str, bool]:
"""Returns the guild permissions needed to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_guild_permissions", {})
def required_bot_guild_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to have in this guild in order to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.bot_has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_bot_guild_permissions", {})
def qualified_name(self) -> str:
""":class:`str`: Retrieves the fully qualified command name.
.. versionadded:: 2.1
"""
return str(self.name)
def description(self) -> str:
"""The description the command should have in Discord. Should be 1-100 characters long."""
return self._description or DEFAULT_SLASH_DESCRIPTION
def description(self, new_description: str) -> None:
self._description = new_description
def is_guild(self) -> bool:
""":class:`bool`: Returns ``True`` if this command is or should be registered to any guilds."""
guild_only_ids = set(self.command_ids.keys())
guild_only_ids.discard(None)
return bool(self.guild_ids_to_rollout or guild_only_ids)
def guild_ids(self) -> Set[int]:
"""Returns a :class:`set` containing all guild ID's this command is registered to."""
# TODO: Is this worthwhile?
guild_only_ids = set(self.command_ids.keys())
guild_only_ids.discard(None)
# ignore explanation: Mypy says that guild_only_ids can contain None due to self.command_ids.keys() having
# None being typehinted, but we remove None before returning it.
return guild_only_ids # type: ignore
def add_guild_rollout(self, guild: Union[int, Guild]) -> None:
"""Adds a Guild to the command to be rolled out to when the rollout is run.
Parameters
----------
guild: Union[:class:`int`, :class:`Guild`]
Guild or Guild ID to add this command to roll out to.
"""
self.guild_ids_to_rollout.add(guild.id if isinstance(guild, Guild) else guild)
def is_global(self) -> bool:
""":class:`bool`: Returns ``True`` if this command is or should be a global command."""
return self.force_global or not self.is_guild or None in self.command_ids
def get_signature(
self, guild_id: Optional[int] = None
) -> Tuple[Optional[str], int, Optional[int]]:
"""Returns a command signature with the given guild ID.
Parameters
----------
guild_id: Optional[:class:`None`]
Guild ID to make the signature for. If set to ``None``, it acts as a global command signature.
Returns
-------
Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]
A tuple that acts as a signature made up of the name, type, and guild ID.
"""
# noinspection PyUnresolvedReferences
return self.name, self.type.value, guild_id
def get_rollout_signatures(self) -> Set[Tuple[str, int, Optional[int]]]:
"""Returns all signatures that this command wants to roll out to.
Command signatures are made up of the command name, command type, and Guild ID (``None`` for global).
Returns
-------
Set[Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]]
A set of tuples that act as signatures.
"""
ret = set()
if self.is_global:
ret.add(self.get_signature(None))
for guild_id in self.guild_ids_to_rollout:
ret.add(self.get_signature(guild_id))
return ret
def get_signatures(self) -> Set[Tuple[str, int, Optional[int]]]:
"""Returns all the signatures that this command has.
Command signatures are made up of the command name, command type, and Guild ID (``None`` for global).
Returns
-------
Set[Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]]
A set of tuples that act as signatures.
"""
ret = set()
if self.is_global:
ret.add(self.get_signature(None))
if self.is_guild:
for guild_id in self.guild_ids:
ret.add(self.get_signature(guild_id))
return ret
def get_name_localization_payload(self) -> Optional[Dict[str, str]]:
if self.name_localizations:
ret = {}
for locale, name in self.name_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = name
else:
ret[locale] = name
return ret
return None
def get_description_localization_payload(self) -> Optional[dict]:
if self.description_localizations:
ret = {}
for locale, description in self.description_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = description
else:
ret[locale] = description
return ret
return None
def get_default_member_permissions_value(self) -> Optional[int]:
if (
isinstance(self.default_member_permissions, int)
or self.default_member_permissions is None
):
return self.default_member_permissions
return self.default_member_permissions.value
def get_payload(self, guild_id: Optional[int]) -> dict:
"""Makes an Application Command payload for this command to upsert to Discord with the given Guild ID.
Parameters
----------
guild_id: Optional[:class:`int`]
Guild ID that this payload is for. If set to ``None``, it will be a global command payload instead.
Returns
-------
:class:`dict`
Dictionary payload to upsert to Discord.
"""
# Below is to make PyCharm stop complaining that self.type.value isn't valid.
# noinspection PyUnresolvedReferences
ret = {
"type": self.type.value,
"name": str(
self.name
), # Might as well stringify the name, will come in handy if people try using numbers.
"description": str(self.description), # Might as well do the same with the description.
"name_localizations": self.get_name_localization_payload(),
"description_localizations": self.get_description_localization_payload(),
}
if self.default_member_permissions is not None:
# While Discord accepts it as an int, they will respond back with the permissions value as a string because
# the permissions bitfield can get too big for them. Stringify it for easy payload-comparison.
ret["default_member_permissions"] = str(self.get_default_member_permissions_value())
if guild_id: # Guild-command specific payload options.
ret["guild_id"] = guild_id
# Global command specific payload options.
elif self.dm_permission is not None:
ret["dm_permission"] = self.dm_permission
else:
# Discord seems to send back the DM permission as True regardless if we sent it or not, so we send as
# the default (True) to ensure payload parity for comparisons.
ret["dm_permission"] = True
ret["nsfw"] = self.nsfw
return ret
def parse_discord_response(
self,
state: ConnectionState,
data: Union[ApplicationCommandInteractionData, ApplicationCommandPayload],
) -> None:
"""Parses the application command creation/update response from Discord.
Parameters
----------
state: :class:`ConnectionState`
Connection state to use internally in the command.
data: Union[:class:`ApplicationCommandInteractionData`, :class:`ApplicationCommand`]
Raw dictionary data from Discord.
"""
self._state = state
command_id = int(data["id"])
if guild_id := data.get("guild_id", None):
guild_id = int(guild_id)
self.command_ids[guild_id] = command_id
self.guild_ids_to_rollout.add(guild_id)
else:
self.command_ids[None] = command_id
def is_payload_valid(
self, raw_payload: ApplicationCommandPayload, guild_id: Optional[int] = None
) -> bool:
"""Checks if the given raw application command interaction payload from Discord is possibly valid for
this command.
Note that while this may return ``True`` for a given payload, that doesn't mean that the payload is fully
correct for this command. Discord doesn't send data for parameters that are optional and aren't supplied by
the user.
Parameters
----------
raw_payload: :class:`dict`
Application command interaction payload from Discord.
guild_id: Optional[:class:`int`]
Guild ID that the payload is from. If it's from a global command, this should be ``None``
Returns
-------
:class:`bool`
``True`` if the given payload is possibly valid for this command. ``False`` otherwise.
"""
cmd_payload = self.get_payload(guild_id)
if cmd_payload.get("guild_id", 0) != int(raw_payload.get("guild_id", 0)):
_log.debug("Guild ID doesn't match raw payload, not valid payload.")
return False
if not check_dictionary_values(
cmd_payload,
raw_payload, # type: ignore # specificity of typeddicts doesnt matter in validation
"default_member_permissions",
"description",
"type",
"name",
"name_localizations",
"description_localizations",
"dm_permission",
"nsfw",
):
_log.debug("Failed check dictionary values, not valid payload.")
return False
if len(cmd_payload.get("options", [])) != len(raw_payload.get("options", [])):
_log.debug("Option amount between commands not equal, not valid payload.")
return False
for cmd_option in cmd_payload.get("options", []):
# I absolutely do not trust Discord or us ordering things nicely, so check through both.
found_correct_value = False
for raw_option in raw_payload.get("options", []):
if cmd_option["name"] == raw_option["name"]:
found_correct_value = True
# At this time, ApplicationCommand options are identical between locally-generated payloads and
# payloads from Discord. If that were to change, switch from a recursive setup and manually
# check_dictionary_values.
if not deep_dictionary_check(cmd_option, raw_option): # type: ignore
# its a dict check so typeddicts do not matter
_log.debug("Options failed deep dictionary checks, not valid payload.")
return False
break
if not found_correct_value:
_log.debug("Discord is missing an option we have, not valid payload.")
return False
return True
def is_interaction_valid(self, interaction: Interaction) -> bool:
"""Checks if the interaction given is possibly valid for this command.
If the command has more parameters (especially optionals) than the interaction coming in, this may cause a
desync between your bot and Discord.
Parameters
----------
interaction: :class:`Interaction`
Interaction to validate.
Returns
-------
:class:`bool`
``True`` If the interaction could possibly be for this command, ``False`` otherwise.
"""
data = interaction.data
if data is None:
raise ValueError("Discord did not provide us with interaction data")
our_payload = self.get_payload(data.get("guild_id", None))
def _recursive_subcommand_check(inter_pos: dict, cmd_pos: dict) -> bool:
"""A small recursive wrapper that checks for subcommand(s) (group(s)).
Parameters
----------
inter_pos: :class:`dict`
Current command position from the payload in the interaction.
cmd_pos: :class:`dict`
Current command position from the payload for the local command.
Returns
-------
:class:`bool`
``True`` if the payloads match, ``False`` otherwise.
"""
inter_options = inter_pos.get("options")
cmd_options = cmd_pos.get("options", {})
if inter_options is None:
raise ValueError("Interaction options was not provided")
our_options = {opt["name"]: opt for opt in cmd_options}
if (
len(inter_options) == 1
and ( # If the length is only 1, it might be a subcommand (group).
inter_options[0]["type"]
in (
ApplicationCommandOptionType.sub_command.value,
ApplicationCommandOptionType.sub_command_group.value,
)
)
and ( # This checks if it's a subcommand (group).
found_opt := our_options.get(
inter_options[0]["name"]
) # This checks if the name matches an option.
)
and inter_options[0]["type"] == found_opt["type"]
): # And this makes sure both are the same type.
return _recursive_subcommand_check(
inter_options[0], found_opt
) # If all of the above pass, recurse.
return _option_check(inter_options, cmd_options)
def _option_check(inter_options: dict, cmd_options: dict) -> bool:
"""Checks if the two given command payloads have matching options.
Parameters
----------
inter_options: :class:`dict`
Command option data from the interaction.
cmd_options: :class:`dict`
Command option data from the local command.
Returns
-------
:class:`bool`
``True`` if the options match, ``False`` otherwise.
"""
all_our_options = {}
required_options = {}
for our_opt in cmd_options:
all_our_options[our_opt["name"]] = our_opt
if our_opt.get("required"):
required_options[our_opt["name"]] = our_opt
all_inter_options = {inter_opt["name"]: inter_opt for inter_opt in inter_options}
if len(all_our_options) >= len(all_inter_options):
# If we have more options (including options) than the interaction, we are good to proceed.
all_our_options_copy = all_our_options.copy()
all_inter_options_copy = all_inter_options.copy()
# Begin checking required options.
for our_opt_name, our_opt in required_options.items():
if inter_opt := all_inter_options.get(our_opt_name):
if (
inter_opt["name"] == our_opt["name"]
and inter_opt["type"] == our_opt["type"]
):
all_our_options_copy.pop(our_opt_name)
all_inter_options_copy.pop(our_opt_name)
else:
_log.debug(
"%s Required option don't match name and/or type.", self.error_name
)
return False # Options don't match name and/or type.
else:
_log.debug("%s Inter missing required option.", self.error_name)
return False # Required option wasn't found.
# Begin checking optional arguments.
for (
inter_opt_name,
inter_opt,
) in all_inter_options_copy.items(): # Should only contain optionals now.
if our_opt := all_our_options_copy.get(inter_opt_name):
if not (
inter_opt["name"] == our_opt["name"]
and inter_opt["type"] == our_opt["type"]
):
_log.debug(
"%s Optional option don't match name and/or type.", self.error_name
)
return False # Options don't match name and/or type.
else:
_log.debug("%s Inter has option that we don't.", self.error_name)
return False # They have an option name that we don't.
else:
_log.debug(
"%s We have less options than them: %s vs %s",
self.error_name,
all_our_options,
all_inter_options,
)
return False # Interaction has more options than we do.
return True # No checks failed.
# caring about typeddict specificity will cause issues down the line
if not check_dictionary_values(our_payload, data, "name", "guild_id", "type"): # type: ignore
_log.debug("%s Failed basic dictionary check.", self.error_name)
return False
data_options = data.get("options")
payload_options = our_payload.get("options")
if data_options and payload_options:
return _recursive_subcommand_check(data, our_payload) # type: ignore
if data_options is None and payload_options is None:
return True # User and Message commands don't have options.
_log.debug(
"%s Mismatch between data and payload options: %s vs %s",
self.error_name,
data_options,
payload_options,
)
# There is a mismatch between the two, fail it.
return False
def from_callback(
self,
callback: Optional[Callable] = None,
option_class: Optional[Type[BaseCommandOption]] = BaseCommandOption,
) -> None:
super().from_callback(callback=callback, option_class=option_class)
async def call_from_interaction(self, interaction: Interaction) -> None:
"""|coro|
Calls the callback via the given :class:`Interaction`, relying on the locally
stored :class:`ConnectionState` object.
Parameters
----------
interaction: :class:`Interaction`
Interaction corresponding to the use of the command.
"""
await self.call(self._state, interaction) # type: ignore
async def call(self, state: ConnectionState, interaction: Interaction) -> None:
"""|coro|
Calls the callback via the given :class:`Interaction`, using the given :class:`ConnectionState` to get resolved
objects if needed and available.
Parameters
----------
state: :class:`ConnectionState`
State object to get resolved objects from.
interaction: :class:`Interaction`
Interaction corresponding to the use of the command.
"""
raise NotImplementedError
def check_against_raw_payload(
self, raw_payload: ApplicationCommandPayload, guild_id: Optional[int] = None
) -> bool:
warnings.warn(
".check_against_raw_payload() is deprecated, please use .is_payload_valid instead.",
stacklevel=2,
category=FutureWarning,
)
return self.is_payload_valid(raw_payload, guild_id)
def get_guild_payload(self, guild_id: int):
warnings.warn(
".get_guild_payload is deprecated, use .get_payload(guild_id) instead.",
stacklevel=2,
category=FutureWarning,
)
return self.get_payload(guild_id)
def global_payload(self) -> dict:
warnings.warn(
".global_payload is deprecated, use .get_payload(None) instead.",
stacklevel=2,
category=FutureWarning,
)
return self.get_payload(None)
class UserApplicationCommand(BaseApplicationCommand):
"""Class representing a user context menu command."""
def __init__(
self,
name: Optional[str] = None,
*,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
callback: Optional[Callable] = None,
guild_ids: Optional[Iterable[int]] = None,
dm_permission: Optional[bool] = None,
default_member_permissions: Optional[Union[Permissions, int]] = None,
nsfw: bool = False,
parent_cog: Optional[ClientCog] = None,
force_global: bool = False,
) -> None:
"""Represents a User Application Command that will give the user to the given callback, able to be registered to
multiple guilds or globally.
Parameters
----------
name: :class:`str`
Name of the command. Can be uppercase with spaces.
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the subcommand for users of specific locales. The locale code should be the key, with the
localized name as the value.
callback: :data:`~typing.Callable`
Callback to run with the application command is called.
guild_ids: Iterable[:class:`int`]
An iterable list of guild ID's that the application command should register to.
dm_permission: :class:`bool`
If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being
usable in DMs. Only for global commands, but will not error on guild.
default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]]
Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for
example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by
default. Server owners CAN override the permission requirements.
nsfw: :class:`bool`
Whether the command can only be used in age-restricted channels. Defaults to ``False``.
.. versionadded:: 2.4
parent_cog: Optional[:class:`ClientCog`]
``ClientCog`` to forward to the callback as the ``self`` argument.
force_global: :class:`bool`
If this command should be registered as a global command, ALONG WITH all guild IDs set.
"""
super().__init__(
name=name,
name_localizations=name_localizations,
description="",
callback=callback,
cmd_type=ApplicationCommandType.user,
guild_ids=guild_ids,
dm_permission=dm_permission,
default_member_permissions=default_member_permissions,
nsfw=nsfw,
parent_cog=parent_cog,
force_global=force_global,
)
def description(self) -> str:
return ""
def description(self, new_desc: str):
raise ValueError("UserApplicationCommands cannot have a description set.")
async def call(self, state: ConnectionState, interaction: Interaction) -> None:
await self.invoke_callback_with_hooks(
state, interaction, args=(get_users_from_interaction(state, interaction)[0],)
)
def from_callback(
self,
callback: Optional[Callable] = None,
option_class: Optional[Type[BaseCommandOption]] = None,
) -> None:
super().from_callback(callback, option_class=option_class)
CallbackWrapperMixin.modify(self)
class Locale(StrEnum):
da = "da"
"""Danish | Dansk"""
de = "de"
"""German | Deutsch"""
en_GB = "en-GB"
"""English, UK | English, UK"""
en_US = "en-US"
"""English, US | English, US"""
es_ES = "es-ES"
"""Spanish | Español"""
fr = "fr"
"""French | Français"""
hr = "hr"
"""Croatian | Hrvatski"""
id = "id"
"""Indonesian | Bahasa Indonesia
.. versionadded:: 2.4
"""
it = "it"
"""Italian | Italiano"""
lt = "lt"
"""Lithuanian | Lietuviškai"""
hu = "hu"
"""Hungarian | Magyar"""
nl = "nl"
"""Dutch | Nederlands"""
no = "no"
"""Norwegian | Norsk"""
pl = "pl"
"""Polish | Polski"""
pt_BR = "pt-BR"
"""Portuguese, Brazilian | Português do Brasil"""
ro = "ro"
"""Romanian, Romania | Română"""
fi = "fi"
"""Finnish | Suomi"""
sv_SE = "sv-SE"
"""Swedish | Svenska"""
vi = "vi"
"""Vietnamese | Tiếng Việt"""
tr = "tr"
"""Turkish | Türkçe"""
cs = "cs"
"""Czech | Čeština"""
el = "el"
"""Greek | Ελληνικά"""
bg = "bg"
"""Bulgarian | български"""
ru = "ru"
"""Russian | Pусский""" # noqa: RUF001
uk = "uk"
"""Ukrainian | Українська"""
hi = "hi"
"""Hindi | हिन्दी"""
th = "th"
"""Thai | ไทย"""
zh_CN = "zh-CN"
"""Chinese, China | 中文"""
ja = "ja"
"""Japanese | 日本語"""
zh_TW = "zh-TW"
"""Chinese, Taiwan | 繁體中文"""
ko = "ko"
"""Korean | 한국어"""
class Permissions(BaseFlags):
"""Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual
bits using the properties as if they were regular bools. This allows
you to edit permissions.
.. versionchanged:: 1.3
You can now use keyword arguments to initialize :class:`Permissions`
similar to :meth:`update`.
.. container:: operations
.. describe:: x == y
Checks if two permissions are equal.
.. describe:: x != y
Checks if two permissions are not equal.
.. describe:: x <= y
Checks if a permission is a subset of another permission.
.. describe:: x >= y
Checks if a permission is a superset of another permission.
.. describe:: x < y
Checks if a permission is a strict subset of another permission.
.. describe:: x > y
Checks if a permission is a strict superset of another permission.
.. describe:: hash(x)
Return the permission's hash.
.. describe:: iter(x)
Returns an iterator of ``(perm, value)`` pairs. This allows it
to be, for example, constructed as a dict or a list of pairs.
Note that aliases are not shown.
Attributes
----------
value: :class:`int`
The raw value. This value is a bit array field of a 53-bit integer
representing the currently available permissions. You should query
permissions via the properties rather than using this raw value.
"""
__slots__ = ()
def __init__(self, permissions: int = 0, **kwargs: bool) -> None:
if not isinstance(permissions, int):
raise TypeError(
f"Expected int parameter, received {permissions.__class__.__name__} instead."
)
self.value = permissions
for key, value in kwargs.items():
if key not in self.VALID_FLAGS:
raise TypeError(f"{key!r} is not a valid permission name.")
setattr(self, key, value)
def is_subset(self, other: Permissions) -> bool:
"""Returns ``True`` if self has the same or fewer permissions as other."""
if isinstance(other, Permissions):
return (self.value & other.value) == self.value
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}")
def is_superset(self, other: Permissions) -> bool:
"""Returns ``True`` if self has the same or more permissions as other."""
if isinstance(other, Permissions):
return (self.value | other.value) == self.value
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}")
def is_strict_subset(self, other: Permissions) -> bool:
"""Returns ``True`` if the permissions on other are a strict subset of those on self."""
return self.is_subset(other) and self != other
def is_strict_superset(self, other: Permissions) -> bool:
"""Returns ``True`` if the permissions on other are a strict superset of those on self."""
return self.is_superset(other) and self != other
__le__ = is_subset
__ge__ = is_superset
__lt__ = is_strict_subset
__gt__ = is_strict_superset
def none(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
permissions set to ``False``."""
return cls(0)
def all(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
permissions set to ``True``.
"""
return cls(-1)
def all_channel(cls) -> Self:
"""A :class:`Permissions` with all channel-specific permissions set to
``True`` and the guild-specific ones set to ``False``. The guild-specific
permissions are currently:
- :attr:`manage_emojis`
- :attr:`view_audit_log`
- :attr:`view_guild_insights`
- :attr:`manage_guild`
- :attr:`change_nickname`
- :attr:`manage_nicknames`
- :attr:`kick_members`
- :attr:`ban_members`
- :attr:`administrator`
.. versionchanged:: 1.7
Added :attr:`stream`, :attr:`priority_speaker` and :attr:`use_slash_commands` permissions.
.. versionchanged:: 2.0
Added :attr:`create_public_threads`, :attr:`create_private_threads`, :attr:`manage_threads`,
:attr:`use_external_stickers`, :attr:`send_messages_in_threads` and
:attr:`request_to_speak` permissions.
"""
return cls(0b111110110110011111101111111111101010001)
def general(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"General" permissions from the official Discord UI set to ``True``.
.. versionchanged:: 1.7
Permission :attr:`read_messages` is now included in the general permissions, but
permissions :attr:`administrator`, :attr:`create_instant_invite`, :attr:`kick_members`,
:attr:`ban_members`, :attr:`change_nickname` and :attr:`manage_nicknames` are
no longer part of the general permissions.
"""
return cls(0b01110000000010000000010010110000)
def membership(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Membership" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(0b00001100000000000000000000000111)
def text(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Text" permissions from the official Discord UI set to ``True``.
.. versionchanged:: 1.7
Permission :attr:`read_messages` is no longer part of the text permissions.
Added :attr:`use_slash_commands` permission.
.. versionchanged:: 2.0
Added :attr:`create_public_threads`, :attr:`create_private_threads`, :attr:`manage_threads`,
:attr:`send_messages_in_threads` and :attr:`use_external_stickers` permissions.
"""
return cls(0b111110010000000000001111111100001000000)
def voice(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Voice" permissions from the official Discord UI set to ``True``."""
return cls(0b00000011111100000000001100000000)
def stage(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Stage Channel" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(1 << 32)
def stage_moderator(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Stage Moderator" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(0b100000001010000000000000000000000)
def advanced(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Advanced" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(1 << 3)
def update(self, **kwargs: bool) -> None:
r"""Bulk updates this permission object.
Allows you to set multiple attributes by using keyword
arguments. The names must be equivalent to the properties
listed. Extraneous key/value pairs will be silently ignored.
Parameters
----------
\*\*kwargs
A list of key/value pairs to bulk update permissions with.
"""
for key, value in kwargs.items():
if key in self.VALID_FLAGS:
setattr(self, key, value)
def handle_overwrite(self, allow: int, deny: int) -> None:
# Basically this is what's happening here.
# We have an original bit array, e.g. 1010
# Then we have another bit array that is 'denied', e.g. 1111
# And then we have the last one which is 'allowed', e.g. 0101
# We want original OP denied to end up resulting in
# whatever is in denied to be set to 0.
# So 1010 OP 1111 -> 0000
# Then we take this value and look at the allowed values.
# And whatever is allowed is set to 1.
# So 0000 OP2 0101 -> 0101
# The OP is base & ~denied.
# The OP2 is base | allowed.
self.value = (self.value & ~deny) | allow
def create_instant_invite(self) -> int:
""":class:`bool`: Returns ``True`` if the user can create instant invites."""
return 1 << 0
def kick_members(self) -> int:
""":class:`bool`: Returns ``True`` if the user can kick users from the guild."""
return 1 << 1
def ban_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can ban users from the guild."""
return 1 << 2
def administrator(self) -> int:
""":class:`bool`: Returns ``True`` if a user is an administrator. This role overrides all other permissions.
This also bypasses all channel-specific overrides.
"""
return 1 << 3
def manage_channels(self) -> int:
""":class:`bool`: Returns ``True`` if a user can edit, delete, or create channels in the guild.
This also corresponds to the "Manage Channel" channel-specific override."""
return 1 << 4
def manage_guild(self) -> int:
""":class:`bool`: Returns ``True`` if a user can edit guild properties."""
return 1 << 5
def add_reactions(self) -> int:
""":class:`bool`: Returns ``True`` if a user can add reactions to messages."""
return 1 << 6
def view_audit_log(self) -> int:
""":class:`bool`: Returns ``True`` if a user can view the guild's audit log."""
return 1 << 7
def priority_speaker(self) -> int:
""":class:`bool`: Returns ``True`` if a user can be more easily heard while talking."""
return 1 << 8
def stream(self) -> int:
""":class:`bool`: Returns ``True`` if a user can stream in a voice channel."""
return 1 << 9
def read_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can read messages from all or specific text channels."""
return 1 << 10
def view_channel(self) -> int:
""":class:`bool`: An alias for :attr:`read_messages`.
.. versionadded:: 1.3
"""
return 1 << 10
def send_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send messages from all or specific text channels.
This falls under ``Create Posts`` on the UI specifically for Forum Channels.
"""
return 1 << 11
def send_tts_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send TTS messages from all or specific text channels."""
return 1 << 12
def manage_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can delete or pin messages in a text channel.
.. note::
Note that there are currently no ways to edit other people's messages.
"""
return 1 << 13
def embed_links(self) -> int:
""":class:`bool`: Returns ``True`` if a user's messages will automatically be embedded by Discord."""
return 1 << 14
def attach_files(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send files in their messages."""
return 1 << 15
def read_message_history(self) -> int:
""":class:`bool`: Returns ``True`` if a user can read a text channel's previous messages."""
return 1 << 16
def mention_everyone(self) -> int:
""":class:`bool`: Returns ``True`` if a user's @everyone or @here will mention everyone in the text channel."""
return 1 << 17
def external_emojis(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use emojis from other guilds."""
return 1 << 18
def use_external_emojis(self) -> int:
""":class:`bool`: An alias for :attr:`external_emojis`.
.. versionadded:: 1.3
"""
return 1 << 18
def view_guild_insights(self) -> int:
""":class:`bool`: Returns ``True`` if a user can view the guild's insights.
.. versionadded:: 1.3
"""
return 1 << 19
def connect(self) -> int:
""":class:`bool`: Returns ``True`` if a user can connect to a voice channel."""
return 1 << 20
def speak(self) -> int:
""":class:`bool`: Returns ``True`` if a user can speak in a voice channel."""
return 1 << 21
def mute_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can mute other users."""
return 1 << 22
def deafen_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can deafen other users."""
return 1 << 23
def move_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can move users between other voice channels."""
return 1 << 24
def use_voice_activation(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use voice activation in voice channels."""
return 1 << 25
def change_nickname(self) -> int:
""":class:`bool`: Returns ``True`` if a user can change their nickname in the guild."""
return 1 << 26
def manage_nicknames(self) -> int:
""":class:`bool`: Returns ``True`` if a user can change other user's nickname in the guild."""
return 1 << 27
def manage_roles(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create or edit roles less than their role's position.
This also corresponds to the "Manage Permissions" channel-specific override.
"""
return 1 << 28
def manage_permissions(self) -> int:
""":class:`bool`: An alias for :attr:`manage_roles`.
.. versionadded:: 1.3
"""
return 1 << 28
def manage_webhooks(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create, edit, or delete webhooks."""
return 1 << 29
def manage_emojis(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create, edit, or delete emojis."""
return 1 << 30
def manage_emojis_and_stickers(self) -> int:
""":class:`bool`: An alias for :attr:`manage_emojis`.
.. versionadded:: 2.0
"""
return 1 << 30
def use_slash_commands(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use slash commands.
.. versionadded:: 1.7
"""
return 1 << 31
def request_to_speak(self) -> int:
""":class:`bool`: Returns ``True`` if a user can request to speak in a stage channel.
.. versionadded:: 1.7
"""
return 1 << 32
def manage_events(self) -> int:
""":class:`bool`: Returns ``True`` if a user can manage guild events.
.. versionadded:: 2.0
"""
return 1 << 33
def manage_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can manage threads.
.. versionadded:: 2.0
"""
return 1 << 34
def create_public_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create public threads.
.. versionadded:: 2.0
"""
return 1 << 35
def create_private_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create private threads.
.. versionadded:: 2.0
"""
return 1 << 36
def external_stickers(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use stickers from other guilds.
.. versionadded:: 2.0
"""
return 1 << 37
def use_external_stickers(self) -> int:
""":class:`bool`: An alias for :attr:`external_stickers`.
.. versionadded:: 2.0
"""
return 1 << 37
def send_messages_in_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send messages in threads.
This falls under ``Send Messages in Posts`` on the UI specifically for Forum channels.
.. versionadded:: 2.0
"""
return 1 << 38
def start_embedded_activities(self) -> int:
""":class:`bool`: Returns ``True`` if a user can launch activities in a voice channel.
.. versionadded:: 2.0
"""
return 1 << 39
def moderate_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can moderate members (add timeouts).
Referred to as ``Timeout Members`` in the discord client.
.. versionadded:: 2.0
"""
return 1 << 40
MISSING: Any = _MissingSentinel()
The provided code snippet includes necessary dependencies for implementing the `user_command` function. Write a Python function `def user_command( name: Optional[str] = None, *, name_localizations: Optional[Dict[Union[Locale, str], str]] = None, guild_ids: Optional[Iterable[int]] = MISSING, dm_permission: Optional[bool] = None, default_member_permissions: Optional[Union[Permissions, int]] = None, nsfw: bool = False, force_global: bool = False, )` to solve the following problem:
Creates a User context command from the decorated function. Used inside :class:`ClientCog`'s or something that subclasses it. Parameters ---------- name: :class:`str` Name of the command that users will see. If not set, it defaults to the name of the callback. name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`] Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the value guild_ids: Optional[Iterable[:class:`int`]] IDs of :class:`Guild`'s to add this command to. If not passed and :attr:`Client.default_guild_ids` is set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command. dm_permission: :class:`bool` If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being usable in DMs. Only for global commands, but will not error on guild. default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]] Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements. nsfw: :class:`bool` Whether the command can only be used in age-restricted channels. Defaults to ``False``. .. versionadded:: 2.4 force_global: :class:`bool` If True, will force this command to register as a global command, even if ``guild_ids`` is set. Will still register to guilds. Has no effect if ``guild_ids`` are never set or added to.
Here is the function:
def user_command(
name: Optional[str] = None,
*,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
guild_ids: Optional[Iterable[int]] = MISSING,
dm_permission: Optional[bool] = None,
default_member_permissions: Optional[Union[Permissions, int]] = None,
nsfw: bool = False,
force_global: bool = False,
):
"""Creates a User context command from the decorated function.
Used inside :class:`ClientCog`'s or something that subclasses it.
Parameters
----------
name: :class:`str`
Name of the command that users will see. If not set, it defaults to the name of the callback.
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the command for users of specific locales. The locale code should be the key, with the localized
name as the value
guild_ids: Optional[Iterable[:class:`int`]]
IDs of :class:`Guild`'s to add this command to. If not passed and :attr:`Client.default_guild_ids` is
set, then those default guild ids will be used instead. If both of those are unset, then the command will
be a global command.
dm_permission: :class:`bool`
If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being
usable in DMs. Only for global commands, but will not error on guild.
default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]]
Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for
example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by
default. Server owners CAN override the permission requirements.
nsfw: :class:`bool`
Whether the command can only be used in age-restricted channels. Defaults to ``False``.
.. versionadded:: 2.4
force_global: :class:`bool`
If True, will force this command to register as a global command, even if ``guild_ids`` is set. Will still
register to guilds. Has no effect if ``guild_ids`` are never set or added to.
"""
def decorator(func: Callable) -> UserApplicationCommand:
if isinstance(func, BaseApplicationCommand):
raise TypeError("Callback is already an application command.")
return UserApplicationCommand(
callback=func,
name=name,
name_localizations=name_localizations,
guild_ids=guild_ids,
dm_permission=dm_permission,
default_member_permissions=default_member_permissions,
nsfw=nsfw,
force_global=force_global,
)
return decorator | Creates a User context command from the decorated function. Used inside :class:`ClientCog`'s or something that subclasses it. Parameters ---------- name: :class:`str` Name of the command that users will see. If not set, it defaults to the name of the callback. name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`] Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the value guild_ids: Optional[Iterable[:class:`int`]] IDs of :class:`Guild`'s to add this command to. If not passed and :attr:`Client.default_guild_ids` is set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command. dm_permission: :class:`bool` If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being usable in DMs. Only for global commands, but will not error on guild. default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]] Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements. nsfw: :class:`bool` Whether the command can only be used in age-restricted channels. Defaults to ``False``. .. versionadded:: 2.4 force_global: :class:`bool` If True, will force this command to register as a global command, even if ``guild_ids`` is set. Will still register to guilds. Has no effect if ``guild_ids`` are never set or added to. |
160,987 | from __future__ import annotations
import asyncio
import contextlib
import logging
import sys
import warnings
from inspect import Parameter, signature
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Coroutine,
Dict,
Iterable,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
import typing_extensions
from typing_extensions import Annotated
from .abc import GuildChannel
from .channel import (
CategoryChannel,
DMChannel,
ForumChannel,
GroupChannel,
StageChannel,
TextChannel,
VoiceChannel,
)
from .enums import ApplicationCommandOptionType, ApplicationCommandType, ChannelType, Locale
from .errors import (
ApplicationCheckFailure,
ApplicationCommandOptionMissing,
ApplicationError,
ApplicationInvokeError,
)
from .guild import Guild
from .interactions import Interaction
from .member import Member
from .message import Attachment, Message
from .object import Object
from .permissions import Permissions
from .role import Role
from .threads import Thread
from .types.interactions import ApplicationCommandInteractionData
from .user import User
from .utils import MISSING, find, maybe_coroutine, parse_docstring
_log = logging.getLogger(__name__)
The provided code snippet includes necessary dependencies for implementing the `check_dictionary_values` function. Write a Python function `def check_dictionary_values(dict1: dict, dict2: dict, *keywords) -> bool` to solve the following problem:
Helper function to quickly check if 2 dictionaries share the equal value for the same keyword(s). Used primarily for checking against the registered command data from Discord. Will not work great if values inside the dictionary can be or are None. If both dictionaries lack the keyword(s), it can still return True. Parameters ---------- dict1: :class:`dict` First dictionary to compare. dict2: :class:`dict` Second dictionary to compare. keywords: :class:`str` Words to compare both dictionaries to. Returns ------- :class:`bool` True if keyword values in both dictionaries match, False otherwise.
Here is the function:
def check_dictionary_values(dict1: dict, dict2: dict, *keywords) -> bool:
"""Helper function to quickly check if 2 dictionaries share the equal value for the same keyword(s).
Used primarily for checking against the registered command data from Discord.
Will not work great if values inside the dictionary can be or are None.
If both dictionaries lack the keyword(s), it can still return True.
Parameters
----------
dict1: :class:`dict`
First dictionary to compare.
dict2: :class:`dict`
Second dictionary to compare.
keywords: :class:`str`
Words to compare both dictionaries to.
Returns
-------
:class:`bool`
True if keyword values in both dictionaries match, False otherwise.
"""
for keyword in keywords:
if dict1.get(keyword, None) != dict2.get(keyword, None):
_log.debug(
"Failed basic dictionary value check for key %s:\n %s vs %s",
keyword,
dict1.get(keyword, None),
dict2.get(keyword, None),
)
return False
return True | Helper function to quickly check if 2 dictionaries share the equal value for the same keyword(s). Used primarily for checking against the registered command data from Discord. Will not work great if values inside the dictionary can be or are None. If both dictionaries lack the keyword(s), it can still return True. Parameters ---------- dict1: :class:`dict` First dictionary to compare. dict2: :class:`dict` Second dictionary to compare. keywords: :class:`str` Words to compare both dictionaries to. Returns ------- :class:`bool` True if keyword values in both dictionaries match, False otherwise. |
160,988 | from __future__ import annotations
import asyncio
import contextlib
import logging
import sys
import warnings
from inspect import Parameter, signature
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Coroutine,
Dict,
Iterable,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
import typing_extensions
from typing_extensions import Annotated
from .abc import GuildChannel
from .channel import (
CategoryChannel,
DMChannel,
ForumChannel,
GroupChannel,
StageChannel,
TextChannel,
VoiceChannel,
)
from .enums import ApplicationCommandOptionType, ApplicationCommandType, ChannelType, Locale
from .errors import (
ApplicationCheckFailure,
ApplicationCommandOptionMissing,
ApplicationError,
ApplicationInvokeError,
)
from .guild import Guild
from .interactions import Interaction
from .member import Member
from .message import Attachment, Message
from .object import Object
from .permissions import Permissions
from .role import Role
from .threads import Thread
from .types.interactions import ApplicationCommandInteractionData
from .user import User
from .utils import MISSING, find, maybe_coroutine, parse_docstring
_log = logging.getLogger(__name__)
The provided code snippet includes necessary dependencies for implementing the `deep_dictionary_check` function. Write a Python function `def deep_dictionary_check(dict1: dict, dict2: dict) -> bool` to solve the following problem:
Used to check if all keys and values between two dicts are equal, and recurses if it encounters a nested dict.
Here is the function:
def deep_dictionary_check(dict1: dict, dict2: dict) -> bool:
"""Used to check if all keys and values between two dicts are equal, and recurses if it encounters a nested dict."""
if dict1.keys() != dict2.keys():
_log.debug(
"Dict1 and Dict2 keys are not equal, not valid payload.\n %s vs %s",
dict1.keys(),
dict2.keys(),
)
return False
for key in dict1:
if (
isinstance(dict1[key], dict)
and isinstance(dict2[key], dict)
and not deep_dictionary_check(dict1[key], dict2[key])
):
return False
if dict1[key] != dict2[key]:
_log.debug(
"Dict1 and Dict2 values are not equal, not valid payload.\n Key: %s, values %s vs %s",
key,
dict1[key],
dict2[key],
)
return False
return True | Used to check if all keys and values between two dicts are equal, and recurses if it encounters a nested dict. |
160,989 | from __future__ import annotations
import asyncio
import contextlib
import logging
import sys
import warnings
from inspect import Parameter, signature
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Coroutine,
Dict,
Iterable,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
import typing_extensions
from typing_extensions import Annotated
from .abc import GuildChannel
from .channel import (
CategoryChannel,
DMChannel,
ForumChannel,
GroupChannel,
StageChannel,
TextChannel,
VoiceChannel,
)
from .enums import ApplicationCommandOptionType, ApplicationCommandType, ChannelType, Locale
from .errors import (
ApplicationCheckFailure,
ApplicationCommandOptionMissing,
ApplicationError,
ApplicationInvokeError,
)
from .guild import Guild
from .interactions import Interaction
from .member import Member
from .message import Attachment, Message
from .object import Object
from .permissions import Permissions
from .role import Role
from .threads import Thread
from .types.interactions import ApplicationCommandInteractionData
from .user import User
from .utils import MISSING, find, maybe_coroutine, parse_docstring
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class Member(abc.Messageable, _UserTag):
"""Represents a Discord member to a :class:`Guild`.
This implements a lot of the functionality of :class:`User`.
.. container:: operations
.. describe:: x == y
Checks if two members are equal.
Note that this works with :class:`User` instances too.
.. describe:: x != y
Checks if two members are not equal.
Note that this works with :class:`User` instances too.
.. describe:: hash(x)
Returns the member's hash.
.. describe:: str(x)
Returns the member's name with the discriminator.
Attributes
----------
joined_at: Optional[:class:`datetime.datetime`]
An aware datetime object that specifies the date and time in UTC that the member joined the guild.
If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be ``None``.
activities: Tuple[Union[:class:`BaseActivity`, :class:`Spotify`]]
The activities that the user is currently doing.
.. note::
Due to a Discord API limitation, a user's Spotify activity may not appear
if they are listening to a song with a title longer
than 128 characters. See :dpyissue:`1738` for more information.
guild: :class:`Guild`
The guild that the member belongs to.
nick: Optional[:class:`str`]
The guild specific nickname of the user.
pending: :class:`bool`
Whether the member is pending member verification.
.. versionadded:: 1.6
premium_since: Optional[:class:`datetime.datetime`]
An aware datetime object that specifies the date and time in UTC when the member used their
"Nitro boost" on the guild, if available. This could be ``None``.
"""
__slots__ = (
"_roles",
"joined_at",
"premium_since",
"activities",
"guild",
"pending",
"nick",
"_client_status",
"_user",
"_state",
"_avatar",
"_timeout",
"_flags",
)
if TYPE_CHECKING:
name: str
id: int
global_name: Optional[str]
discriminator: str
bot: bool
system: bool
created_at: datetime.datetime
default_avatar: Asset
avatar: Optional[Asset]
dm_channel: Optional[DMChannel]
create_dm = User.create_dm
mutual_guilds: List[Guild]
public_flags: PublicUserFlags
banner: Optional[Asset]
accent_color: Optional[Colour]
accent_colour: Optional[Colour]
def __init__(
self, *, data: MemberWithUserPayload, guild: Guild, state: ConnectionState
) -> None:
self._state: ConnectionState = state
self._user: User = state.store_user(data["user"])
self.guild: Guild = guild
self.joined_at: Optional[datetime.datetime] = utils.parse_time(data.get("joined_at"))
self.premium_since: Optional[datetime.datetime] = utils.parse_time(
data.get("premium_since")
)
self._roles: utils.SnowflakeList = utils.SnowflakeList(map(int, data["roles"]))
self._client_status: Dict[Optional[str], str] = {None: "offline"}
self.activities: Tuple[ActivityTypes, ...] = ()
self.nick: Optional[str] = data.get("nick", None)
self.pending: bool = data.get("pending", False)
self._avatar: Optional[str] = data.get("avatar")
self._timeout: Optional[datetime.datetime] = utils.parse_time(
data.get("communication_disabled_until")
)
self._flags: int = data.get("flags", 0)
def __str__(self) -> str:
return str(self._user)
def __repr__(self) -> str:
return (
f"<Member id={self._user.id} name={self._user.name!r} global_name={self._user.global_name!r}"
+ (f" discriminator={self._user.discriminator!r}" if self.discriminator != "0" else "")
+ f" bot={self._user.bot} nick={self.nick!r} guild={self.guild!r}>"
)
def __eq__(self, other: Any) -> bool:
return isinstance(other, _UserTag) and other.id == self.id
def __ne__(self, other: Any) -> bool:
return not self.__eq__(other)
def __hash__(self) -> int:
return hash(self._user)
def _from_message(cls, *, message: Message, data: MemberPayload) -> Self:
author = message.author
data["user"] = author._to_minimal_user_json() # type: ignore
return cls(data=data, guild=message.guild, state=message._state) # type: ignore
def _update_from_message(self, data: MemberPayload) -> None:
self.joined_at = utils.parse_time(data.get("joined_at"))
self.premium_since = utils.parse_time(data.get("premium_since"))
self._roles = utils.SnowflakeList(map(int, data["roles"]))
self.nick = data.get("nick", None)
self.pending = data.get("pending", False)
self._timeout = utils.parse_time(data.get("communication_disabled_until"))
self._flags = data.get("flags", 0)
def _try_upgrade(
cls, *, data: UserWithMemberPayload, guild: Guild, state: ConnectionState
) -> Union[User, Member]:
# A User object with a 'member' key
try:
member_data = data.pop("member")
except KeyError:
return state.create_user(data)
else:
member_data["user"] = data # type: ignore
return cls(data=member_data, guild=guild, state=state) # type: ignore
def _copy(cls, member: Self) -> Self:
self = cls.__new__(cls) # to bypass __init__
self._roles = utils.SnowflakeList(member._roles, is_sorted=True)
self.joined_at = member.joined_at
self.premium_since = member.premium_since
self._client_status = member._client_status.copy()
self.guild = member.guild
self.nick = member.nick
self.pending = member.pending
self.activities = member.activities
self._state = member._state
self._avatar = member._avatar
self._timeout = member._timeout
self._flags = member._flags
# Reference will not be copied unless necessary by PRESENCE_UPDATE
# See below
self._user = member._user
return self
async def _get_channel(self):
return await self.create_dm()
def _update(self, data: MemberPayload) -> None:
# the nickname change is optional,
# if it isn't in the payload then it didn't change
with contextlib.suppress(KeyError):
self.nick = data["nick"]
with contextlib.suppress(KeyError):
self.pending = data["pending"]
self.premium_since = utils.parse_time(data.get("premium_since"))
self._roles = utils.SnowflakeList(map(int, data["roles"]))
self._avatar = data.get("avatar")
self._timeout = utils.parse_time(data.get("communication_disabled_until"))
self._flags = data.get("flags", 0)
def _presence_update(
self, data: PartialPresenceUpdate, user: UserPayload
) -> Optional[Tuple[User, User]]:
self.activities = tuple((create_activity(self._state, x) for x in data["activities"]))
self._client_status = {
sys.intern(key): sys.intern(value) for key, value in data.get("client_status", {}).items() # type: ignore
}
self._client_status[None] = sys.intern(data["status"])
if len(user) > 1:
return self._update_inner_user(user)
return None
def _update_inner_user(self, user: UserPayload) -> Optional[Tuple[User, User]]:
u = self._user
original = (u.name, u._avatar, u.discriminator, u._public_flags)
# These keys seem to always be available
modified = (
user["username"],
user["avatar"],
user["discriminator"],
user.get("public_flags", 0),
)
if original != modified:
to_return = User._copy(self._user)
u.name, u._avatar, u.discriminator, u._public_flags = modified
# Signal to dispatch on_user_update
return to_return, u
return None
def status(self) -> Union[Status, str]:
"""Union[:class:`Status`, :class:`str`]: The member's overall status. If the value is unknown, then it will be a :class:`str` instead."""
return try_enum(Status, self._client_status[None])
def raw_status(self) -> str:
""":class:`str`: The member's overall status as a string value.
.. versionadded:: 1.5
"""
return self._client_status[None]
def status(self, value: Status) -> None:
# internal use only
self._client_status[None] = str(value)
def mobile_status(self) -> Status:
""":class:`Status`: The member's status on a mobile device, if applicable."""
return try_enum(Status, self._client_status.get("mobile", "offline"))
def desktop_status(self) -> Status:
""":class:`Status`: The member's status on the desktop client, if applicable."""
return try_enum(Status, self._client_status.get("desktop", "offline"))
def web_status(self) -> Status:
""":class:`Status`: The member's status on the web client, if applicable."""
return try_enum(Status, self._client_status.get("web", "offline"))
def is_on_mobile(self) -> bool:
""":class:`bool`: A helper function that determines if a member is active on a mobile device."""
return "mobile" in self._client_status
def colour(self) -> Colour:
""":class:`Colour`: A property that returns a colour denoting the rendered colour
for the member. If the default colour is the one rendered then an instance
of :meth:`Colour.default` is returned.
There is an alias for this named :attr:`color`.
"""
roles = self.roles[1:] # remove @everyone
# highest order of the colour is the one that gets rendered.
# if the highest is the default colour then the next one with a colour
# is chosen instead
for role in reversed(roles):
if role.colour.value:
return role.colour
return Colour.default()
def color(self) -> Colour:
""":class:`Colour`: A property that returns a color denoting the rendered color for
the member. If the default color is the one rendered then an instance of :meth:`Colour.default`
is returned.
There is an alias for this named :attr:`colour`.
"""
return self.colour
def roles(self) -> List[Role]:
"""List[:class:`Role`]: A :class:`list` of :class:`Role` that the member belongs to. Note
that the first element of this list is always the default '@everyone'
role.
These roles are sorted by their position in the role hierarchy.
"""
result = []
g = self.guild
for role_id in self._roles:
role = g.get_role(role_id)
if role:
result.append(role)
result.append(g.default_role)
result.sort()
return result
def mention(self) -> str:
""":class:`str`: Returns a string that allows you to mention the member.
.. versionchanged:: 2.2
The nickname mention syntax is no longer returned as it is deprecated by Discord.
"""
return f"<@{self._user.id}>"
def display_name(self) -> str:
""":class:`str`: Returns the user's display name.
For regular users this is just their username, but
if they have a guild specific nickname then that
is returned instead.
"""
return self.nick or self.name
def display_avatar(self) -> Asset:
""":class:`Asset`: Returns the member's display avatar.
For regular members this is just their avatar, but
if they have a guild specific avatar then that
is returned instead.
.. versionadded:: 2.0
"""
return self.guild_avatar or self._user.avatar or self._user.default_avatar
def guild_avatar(self) -> Optional[Asset]:
"""Optional[:class:`Asset`]: Returns an :class:`Asset` for the guild avatar
the member has. If unavailable, ``None`` is returned.
.. versionadded:: 2.0
"""
if self._avatar is None:
return None
return Asset._from_guild_avatar(self._state, self.guild.id, self.id, self._avatar)
def activity(self) -> Optional[ActivityTypes]:
"""Optional[Union[:class:`BaseActivity`, :class:`Spotify`]]: Returns the primary
activity the user is currently doing. Could be ``None`` if no activity is being done.
.. note::
Due to a Discord API limitation, this may be ``None`` if
the user is listening to a song on Spotify with a title longer
than 128 characters. See :dpyissue:`1738` for more information.
.. note::
A user may have multiple activities, these can be accessed under :attr:`activities`.
"""
if self.activities:
return self.activities[0]
return None
def flags(self) -> MemberFlags:
""":class:`MemberFlags`: Returns the member's flags.
.. versionadded:: 2.6
"""
return MemberFlags._from_value(self._flags)
def mentioned_in(self, message: Message) -> bool:
"""Checks if the member is mentioned in the specified message.
Parameters
----------
message: :class:`Message`
The message to check if you're mentioned in.
Returns
-------
:class:`bool`
Indicates if the member is mentioned in the message.
"""
if message.guild is None or message.guild.id != self.guild.id:
return False
if self._user.mentioned_in(message):
return True
return any(self._roles.has(role.id) for role in message.role_mentions)
def top_role(self) -> Role:
""":class:`Role`: Returns the member's highest role.
This is useful for figuring where a member stands in the role
hierarchy chain.
"""
guild = self.guild
if len(self._roles) == 0:
return guild.default_role
return max(guild.get_role(rid) or guild.default_role for rid in self._roles)
def guild_permissions(self) -> Permissions:
""":class:`Permissions`: Returns the member's guild permissions.
This only takes into consideration the guild permissions
and not most of the implied permissions or any of the
channel permission overwrites. For 100% accurate permission
calculation, please use :meth:`abc.GuildChannel.permissions_for`.
This does take into consideration guild ownership and the
administrator implication.
"""
if self.guild.owner_id == self.id:
return Permissions.all()
base = Permissions.none()
for r in self.roles:
base.value |= r.permissions.value
if base.administrator:
return Permissions.all()
return base
def voice(self) -> Optional[VoiceState]:
"""Optional[:class:`VoiceState`]: Returns the member's current voice state."""
return self.guild._voice_state_for(self._user.id)
def communication_disabled_until(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: A datetime object that represents
the time in which the member will be able to interact again.
.. note::
This is ``None`` if the user has no timeout.
.. versionadded:: 2.0
"""
if self._timeout is None or self._timeout < utils.utcnow():
return None
return self._timeout
async def ban(
self,
*,
delete_message_seconds: Optional[int] = None,
delete_message_days: Optional[Literal[0, 1, 2, 3, 4, 5, 6, 7]] = None,
reason: Optional[str] = None,
) -> None:
"""|coro|
Bans this member. Equivalent to :meth:`Guild.ban`.
"""
await self.guild.ban(
self,
reason=reason,
delete_message_seconds=delete_message_seconds,
delete_message_days=delete_message_days,
)
async def unban(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Unbans this member. Equivalent to :meth:`Guild.unban`.
"""
await self.guild.unban(self, reason=reason)
async def kick(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Kicks this member. Equivalent to :meth:`Guild.kick`.
"""
await self.guild.kick(self, reason=reason)
async def timeout(
self,
timeout: Union[datetime.datetime, datetime.timedelta],
*,
reason: Optional[str] = None,
) -> None:
"""|coro|
Times out this member.
.. note::
This is a more direct method of timing out a member.
You can also time out members using :meth:`Member.edit`.
.. versionadded:: 2.0
Parameters
----------
timeout: Optional[Union[:class:`~datetime.datetime`, :class:`~datetime.timedelta`]]
The time until the member should not be timed out.
Set this to None to disable their timeout.
reason: Optional[:class:`str`]
The reason for editing this member. Shows up on the audit log.
"""
await self.edit(timeout=timeout, reason=reason)
async def edit(
self,
*,
nick: Optional[str] = MISSING,
mute: bool = MISSING,
deafen: bool = MISSING,
suppress: bool = MISSING,
roles: List[abc.Snowflake] = MISSING,
voice_channel: Optional[VocalGuildChannel] = MISSING,
reason: Optional[str] = None,
timeout: Optional[Union[datetime.datetime, datetime.timedelta]] = MISSING,
flags: MemberFlags = MISSING,
bypass_verification: bool = MISSING,
) -> Optional[Member]:
"""|coro|
Edits the member's data.
Depending on the parameter passed, this requires different permissions listed below:
+---------------------+--------------------------------------+
| Parameter | Permission |
+---------------------+--------------------------------------+
| nick | :attr:`Permissions.manage_nicknames` |
+---------------------+--------------------------------------+
| mute | :attr:`Permissions.mute_members` |
+---------------------+--------------------------------------+
| deafen | :attr:`Permissions.deafen_members` |
+---------------------+--------------------------------------+
| roles | :attr:`Permissions.manage_roles` |
+---------------------+--------------------------------------+
| voice_channel | :attr:`Permissions.move_members` |
+---------------------+--------------------------------------+
| timeout | :attr:`Permissions.moderate_members` |
+---------------------+--------------------------------------+
| bypass_verification | :attr:`Permissions.moderate_members` |
+---------------------+--------------------------------------+
All parameters are optional.
.. versionchanged:: 1.1
Can now pass ``None`` to ``voice_channel`` to kick a member from voice.
.. versionchanged:: 2.0
The newly member is now optionally returned, if applicable.
Parameters
----------
nick: Optional[:class:`str`]
The member's new nickname. Use ``None`` to remove the nickname.
mute: :class:`bool`
Indicates if the member should be guild muted or un-muted.
deafen: :class:`bool`
Indicates if the member should be guild deafened or un-deafened.
suppress: :class:`bool`
Indicates if the member should be suppressed in stage channels.
.. versionadded:: 1.7
roles: List[:class:`Role`]
The member's new list of roles. This *replaces* the roles.
voice_channel: Optional[:class:`VoiceChannel`]
The voice channel to move the member to.
Pass ``None`` to kick them from voice.
reason: Optional[:class:`str`]
The reason for editing this member. Shows up on the audit log.
timeout: Optional[Union[:class:`~datetime.datetime`, :class:`~datetime.timedelta`]
The time until the member should not be timed out.
Set this to None to disable their timeout.
.. versionadded:: 2.0
flags: :class:`~nextcord.MemberFlags`
The flags to set for this member.
Currently only :class:`~nextcord.MemberFlags.bypasses_verification` is able to be set.
.. versionadded:: 2.6
bypass_verification: :class:`bool`
Indicates if the member should be allowed to bypass the guild verification requirements.
.. versionadded:: 2.6
Raises
------
Forbidden
You do not have the proper permissions to the action requested.
HTTPException
The operation failed.
Returns
-------
Optional[:class:`.Member`]
The newly updated member, if applicable. This is only returned
when certain fields are updated.
"""
http = self._state.http
guild_id = self.guild.id
me = self._state.self_id == self.id
payload: Dict[str, Any] = {}
if nick is not MISSING:
nick = nick or ""
if me:
await http.change_my_nickname(guild_id, nick, reason=reason)
else:
payload["nick"] = nick
if deafen is not MISSING:
payload["deaf"] = deafen
if mute is not MISSING:
payload["mute"] = mute
if suppress is not MISSING:
if self.voice is None:
raise TypeError(
"You can only suppress members which are connected to a voice channel"
)
voice_state_payload = {
"channel_id": self.voice.channel.id, # type: ignore # id should exist
"suppress": suppress,
}
if suppress or self.bot:
voice_state_payload["request_to_speak_timestamp"] = None
if me:
await http.edit_my_voice_state(guild_id, voice_state_payload)
else:
if not suppress:
voice_state_payload["request_to_speak_timestamp"] = utils.utcnow().isoformat()
await http.edit_voice_state(guild_id, self.id, voice_state_payload)
if voice_channel is not MISSING:
payload["channel_id"] = voice_channel and voice_channel.id
if roles is not MISSING:
payload["roles"] = tuple(r.id for r in roles)
if isinstance(timeout, datetime.timedelta):
payload["communication_disabled_until"] = (utils.utcnow() + timeout).isoformat()
elif isinstance(timeout, datetime.datetime):
payload["communication_disabled_until"] = timeout.isoformat()
elif timeout is None:
payload["communication_disabled_until"] = None
elif timeout is MISSING:
pass
else:
raise TypeError(
"Timeout must be a `datetime.datetime` or `datetime.timedelta`"
f"not {timeout.__class__.__name__}"
)
if flags is MISSING:
flags = MemberFlags()
if bypass_verification is not MISSING:
flags.bypasses_verification = bypass_verification
if flags.value != 0:
payload["flags"] = flags.value
if payload:
data = await http.edit_member(guild_id, self.id, reason=reason, **payload)
return Member(data=data, guild=self.guild, state=self._state)
return None
async def request_to_speak(self) -> None:
"""|coro|
Request to speak in the connected channel.
Only applies to stage channels.
.. note::
Requesting members that are not the client is equivalent
to :attr:`.edit` providing ``suppress`` as ``False``.
.. versionadded:: 1.7
Raises
------
Forbidden
You do not have the proper permissions to the action requested.
HTTPException
The operation failed.
"""
payload = {
"channel_id": self.voice.channel.id, # type: ignore # should exist
"request_to_speak_timestamp": utils.utcnow().isoformat(),
}
if self._state.self_id != self.id:
payload["suppress"] = False
await self._state.http.edit_voice_state(self.guild.id, self.id, payload)
else:
await self._state.http.edit_my_voice_state(self.guild.id, payload)
async def move_to(
self, channel: Optional[VocalGuildChannel], *, reason: Optional[str] = None
) -> None:
"""|coro|
Moves a member to a new voice channel (they must be connected first).
You must have the :attr:`~Permissions.move_members` permission to
use this.
This raises the same exceptions as :meth:`edit`.
.. versionchanged:: 1.1
Can now pass ``None`` to kick a member from voice.
Parameters
----------
channel: Optional[:class:`VoiceChannel`]
The new voice channel to move the member to.
Pass ``None`` to kick them from voice.
reason: Optional[:class:`str`]
The reason for doing this action. Shows up on the audit log.
"""
await self.edit(voice_channel=channel, reason=reason)
async def disconnect(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Disconnects a member from the voice channel they are connected to.
You must have the :attr:`~Permissions.move_members` permission to
use this.
This raises the same exceptions as :meth:`edit`.
Parameters
----------
reason: Optional[:class:`str`]
The reason for doing this action. Shows up on the audit log.
"""
await self.edit(voice_channel=None, reason=reason)
async def add_roles(
self, *roles: Snowflake, reason: Optional[str] = None, atomic: bool = True
) -> None:
r"""|coro|
Gives the member a number of :class:`Role`\s.
You must have the :attr:`~Permissions.manage_roles` permission to
use this, and the added :class:`Role`\s must appear lower in the list
of roles than the highest role of the member.
Parameters
----------
\*roles: :class:`abc.Snowflake`
An argument list of :class:`abc.Snowflake` representing a :class:`Role`
to give to the member.
reason: Optional[:class:`str`]
The reason for adding these roles. Shows up on the audit log.
atomic: :class:`bool`
Whether to atomically add roles. This will ensure that multiple
operations will always be applied regardless of the current
state of the cache.
Raises
------
Forbidden
You do not have permissions to add these roles.
HTTPException
Adding roles failed.
"""
if not atomic:
new_roles: list[Snowflake] = utils.unique(
Object(id=r.id) for s in (self.roles[1:], roles) for r in s
)
await self.edit(roles=new_roles, reason=reason)
else:
req = self._state.http.add_role
guild_id = self.guild.id
user_id = self.id
for role in roles:
await req(guild_id, user_id, role.id, reason=reason)
async def remove_roles(
self, *roles: Snowflake, reason: Optional[str] = None, atomic: bool = True
) -> None:
r"""|coro|
Removes :class:`Role`\s from this member.
You must have the :attr:`~Permissions.manage_roles` permission to
use this, and the removed :class:`Role`\s must appear lower in the list
of roles than the highest role of the member.
Parameters
----------
\*roles: :class:`abc.Snowflake`
An argument list of :class:`abc.Snowflake` representing a :class:`Role`
to remove from the member.
reason: Optional[:class:`str`]
The reason for removing these roles. Shows up on the audit log.
atomic: :class:`bool`
Whether to atomically remove roles. This will ensure that multiple
operations will always be applied regardless of the current
state of the cache.
Raises
------
Forbidden
You do not have permissions to remove these roles.
HTTPException
Removing the roles failed.
"""
if not atomic:
new_roles: list[Snowflake] = [
Object(id=r.id) for r in self.roles[1:]
] # remove @everyone
for role in roles:
with contextlib.suppress(ValueError):
new_roles.remove(Object(id=role.id))
await self.edit(roles=new_roles, reason=reason)
else:
req = self._state.http.remove_role
guild_id = self.guild.id
user_id = self.id
for role in roles:
await req(guild_id, user_id, role.id, reason=reason)
def get_role(self, role_id: int, /) -> Optional[Role]:
"""Returns a role with the given ID from roles which the member has.
.. versionadded:: 2.0
Parameters
----------
role_id: :class:`int`
The ID to search for.
Returns
-------
Optional[:class:`Role`]
The role or ``None`` if not found in the member's roles.
"""
return self.guild.get_role(role_id) if self._roles.has(role_id) else None
class ApplicationCommandInteractionData(TypedDict):
id: Snowflake
name: str
type: ApplicationCommandType
options: NotRequired[List[ApplicationCommandInteractionDataOption]]
resolved: NotRequired[ApplicationCommandInteractionDataResolved]
target_id: NotRequired[Snowflake]
class User(BaseUser, abc.Messageable):
"""Represents a Discord user.
.. container:: operations
.. describe:: x == y
Checks if two users are equal.
.. describe:: x != y
Checks if two users are not equal.
.. describe:: hash(x)
Return the user's hash.
.. describe:: str(x)
Returns the user's name with discriminator.
Attributes
----------
name: :class:`str`
The user's username.
id: :class:`int`
The user's unique ID.
global_name: Optional[:class:`str`]
The user's default name, if any.
..versionadded: 2.6
discriminator: :class:`str`
The user's discriminator.
.. warning::
This field is deprecated, and will only return if the user has not yet migrated to the
new `username <https://dis.gd/usernames>`_ update.
.. deprecated:: 2.6
bot: :class:`bool`
Specifies if the user is a bot account.
system: :class:`bool`
Specifies if the user is a system user (i.e. represents Discord officially).
"""
__slots__ = ("_stored",)
def __init__(
self, *, state: ConnectionState, data: Union[PartialUserPayload, UserPayload]
) -> None:
super().__init__(state=state, data=data)
self._stored: bool = False
def __repr__(self) -> str:
return (
f"<User id={self.id} name={self.name!r} global_name={self.global_name!r}"
+ (f" discriminator={self.discriminator!r}" if self.discriminator != "0" else "")
+ f" bot={self.bot}>"
)
def __del__(self) -> None:
try:
if self._stored:
self._state.deref_user(self.id)
except Exception:
pass
def _copy(cls, user: User):
self = super()._copy(user)
self._stored = False
return self
async def _get_channel(self) -> DMChannel:
return await self.create_dm()
def dm_channel(self) -> Optional[DMChannel]:
"""Optional[:class:`DMChannel`]: Returns the channel associated with this user if it exists.
If this returns ``None``, you can create a DM channel by calling the
:meth:`create_dm` coroutine function.
"""
return self._state._get_private_channel_by_user(self.id)
def mutual_guilds(self) -> List[Guild]:
"""List[:class:`Guild`]: The guilds that the user shares with the client.
.. note::
This will only return mutual guilds within the client's internal cache.
.. versionadded:: 1.7
"""
return [guild for guild in self._state._guilds.values() if guild.get_member(self.id)]
async def create_dm(self) -> DMChannel:
"""|coro|
Creates a :class:`DMChannel` with this user.
This should be rarely called, as this is done transparently for most
people.
Returns
-------
:class:`.DMChannel`
The channel that was created.
"""
found = self.dm_channel
if found is not None:
return found
state = self._state
data: DMChannelPayload = await state.http.start_private_message(self.id)
return state.add_dm_channel(data)
class ConnectionState:
if TYPE_CHECKING:
_get_websocket: Callable[..., DiscordWebSocket]
_get_client: Callable[..., Client]
_parsers: Dict[str, Callable[[Dict[str, Any]], None]]
def __init__(
self,
*,
dispatch: Callable,
handlers: Dict[str, Callable],
hooks: Dict[str, Callable],
http: HTTPClient,
loop: asyncio.AbstractEventLoop,
max_messages: Optional[int] = 1000,
application_id: Optional[int] = None,
heartbeat_timeout: float = 60.0,
guild_ready_timeout: float = 2.0,
allowed_mentions: Optional[AllowedMentions] = None,
activity: Optional[BaseActivity] = None,
status: Optional[Status] = None,
intents: Intents = Intents.default(),
chunk_guilds_at_startup: bool = MISSING,
member_cache_flags: MemberCacheFlags = MISSING,
) -> None:
self.loop: asyncio.AbstractEventLoop = loop
self.http: HTTPClient = http
self.max_messages: Optional[int] = max_messages
if self.max_messages is not None and self.max_messages <= 0:
self.max_messages = 1000
self.dispatch: Callable = dispatch
self.handlers: Dict[str, Callable] = handlers
self.hooks: Dict[str, Callable] = hooks
self.shard_count: Optional[int] = None
self._ready_task: Optional[asyncio.Task] = None
self.application_id: Optional[int] = application_id
self.heartbeat_timeout: float = heartbeat_timeout
self.guild_ready_timeout: float = guild_ready_timeout
if self.guild_ready_timeout < 0:
raise ValueError("guild_ready_timeout cannot be negative")
if allowed_mentions is not None and not isinstance(allowed_mentions, AllowedMentions):
raise TypeError("allowed_mentions parameter must be AllowedMentions")
self.allowed_mentions: Optional[AllowedMentions] = allowed_mentions
self._chunk_requests: Dict[Union[int, str], ChunkRequest] = {}
self._chunk_tasks: Dict[Union[int, str], asyncio.Task[None]] = {}
self._background_tasks: Set[asyncio.Task] = set()
if activity is not None:
if not isinstance(activity, BaseActivity):
raise TypeError("activity parameter must derive from BaseActivity.")
raw_activity = activity.to_dict()
else:
raw_activity = activity
raw_status = ("invisible" if status is Status.offline else str(status)) if status else None
if not isinstance(intents, Intents):
raise TypeError(f"intents parameter must be Intent not {type(intents)!r}")
if not intents.guilds:
_log.warning("Guilds intent seems to be disabled. This may cause state related issues.")
if chunk_guilds_at_startup is MISSING:
chunk_guilds_at_startup = intents.members
self._chunk_guilds: bool = chunk_guilds_at_startup
# Ensure these two are set properly
if not intents.members and self._chunk_guilds:
raise ValueError("Intents.members must be enabled to chunk guilds at startup.")
if member_cache_flags is MISSING:
member_cache_flags = MemberCacheFlags.from_intents(intents)
else:
if not isinstance(member_cache_flags, MemberCacheFlags):
raise TypeError(
"member_cache_flags parameter must be MemberCacheFlags "
f"not {type(member_cache_flags)!r}"
)
member_cache_flags._verify_intents(intents)
self.member_cache_flags: MemberCacheFlags = member_cache_flags
self._activity: Optional[ActivityPayload] = raw_activity
self._status: Optional[str] = raw_status
self._intents: Intents = intents
# A set of all application command objects available. Set because duplicates should not exist.
self._application_commands: Set[BaseApplicationCommand] = set()
# A dictionary of all available unique command signatures. Compiled at runtime because needing to iterate
# through all application commands would take far more time. If memory is problematic, perhaps this can go?
self._application_command_signatures: Dict[
Tuple[Optional[str], int, Optional[int]], BaseApplicationCommand
] = {}
# A dictionary of Discord Application Command ID's and the ApplicationCommand object they correspond to.
self._application_command_ids: Dict[int, BaseApplicationCommand] = {}
if not intents.members or member_cache_flags._empty:
self.store_user = self.create_user
self.deref_user = self.deref_user_no_intents
self.parsers = parsers = {}
for attr, func in inspect.getmembers(self):
if attr.startswith("parse_"):
parsers[attr[6:].upper()] = func
self.clear()
def clear(self, *, views: bool = True, modals: bool = True) -> None:
self.user: Optional[ClientUser] = None
# Originally, this code used WeakValueDictionary to maintain references to the
# global user mapping.
# However, profiling showed that this came with two cons:
# 1. The __weakref__ slot caused a non-trivial increase in memory
# 2. The performance of the mapping caused store_user to be a bottleneck.
# Since this is undesirable, a mapping is now used instead with stored
# references now using a regular dictionary with eviction being done
# using __del__. Testing this for memory leaks led to no discernible leaks,
# though more testing will have to be done.
self._users: Dict[int, User] = {}
self._emojis: Dict[int, Emoji] = {}
self._stickers: Dict[int, GuildSticker] = {}
self._guilds: Dict[int, Guild] = {}
# TODO: Why aren't the above and stuff below application_commands declared in __init__?
self._application_commands = set()
# Thought about making these two weakref.WeakValueDictionary's, but the bot could theoretically be holding on
# to them in a dev-defined, which would desync the bot from itself.
self._application_command_signatures = {}
self._application_command_ids = {}
if views:
self._view_store: ViewStore = ViewStore(self)
if modals:
self._modal_store: ModalStore = ModalStore(self)
self._voice_clients: Dict[int, VoiceProtocol] = {}
# LRU of max size 128
self._private_channels: OrderedDict[int, PrivateChannel] = OrderedDict()
# extra dict to look up private channels by user id
self._private_channels_by_user: Dict[int, DMChannel] = {}
if self.max_messages is not None:
self._messages: Optional[Deque[Message]] = deque(maxlen=self.max_messages)
else:
self._messages: Optional[Deque[Message]] = None
def process_chunk_requests(
self, guild_id: int, nonce: Optional[str], members: List[Member], complete: bool
) -> None:
removed = []
for key, request in self._chunk_requests.items():
if request.guild_id == guild_id and request.nonce == nonce:
request.add_members(members)
if complete:
request.done()
removed.append(key)
for key in removed:
del self._chunk_requests[key]
def call_handlers(self, key: str, *args: Any, **kwargs: Any) -> None:
try:
func = self.handlers[key]
except KeyError:
pass
else:
func(*args, **kwargs)
async def call_hooks(self, key: str, *args: Any, **kwargs: Any) -> None:
try:
coro = self.hooks[key]
except KeyError:
pass
else:
await coro(*args, **kwargs)
def self_id(self) -> Optional[int]:
u = self.user
return u.id if u else None
def intents(self) -> Intents:
ret = Intents.none()
ret.value = self._intents.value
return ret
def voice_clients(self) -> List[VoiceProtocol]:
return list(self._voice_clients.values())
def _get_voice_client(self, guild_id: Optional[int]) -> Optional[VoiceProtocol]:
# the keys of self._voice_clients are ints
return self._voice_clients.get(guild_id) # type: ignore
def _add_voice_client(self, guild_id: int, voice: VoiceProtocol) -> None:
self._voice_clients[guild_id] = voice
def _remove_voice_client(self, guild_id: int) -> None:
self._voice_clients.pop(guild_id, None)
def _update_references(self, ws: DiscordWebSocket) -> None:
for vc in self.voice_clients:
vc.main_ws = ws # type: ignore
def store_user(self, data: UserPayload) -> User:
user_id = int(data["id"])
try:
return self._users[user_id]
except KeyError:
user = User(state=self, data=data)
if user.discriminator != "0000":
self._users[user_id] = user
user._stored = True
return user
def deref_user(self, user_id: int) -> None:
self._users.pop(user_id, None)
def create_user(self, data: Union[PartialUserPayload, UserPayload]) -> User:
return User(state=self, data=data)
def deref_user_no_intents(self, user_id: int) -> None:
return
def get_user(self, id: Optional[int]) -> Optional[User]:
# the keys of self._users are ints
return self._users.get(id) # type: ignore
def store_emoji(self, guild: Guild, data: EmojiPayload) -> Emoji:
# the id will be present here
emoji_id = int(data["id"]) # type: ignore
self._emojis[emoji_id] = emoji = Emoji(guild=guild, state=self, data=data)
return emoji
def store_sticker(self, guild: Guild, data: GuildStickerPayload) -> GuildSticker:
sticker_id = int(data["id"])
self._stickers[sticker_id] = sticker = GuildSticker(state=self, data=data)
return sticker
def store_view(self, view: View, message_id: Optional[int] = None) -> None:
self._view_store.add_view(view, message_id)
def store_modal(self, modal: Modal, user_id: Optional[int] = None) -> None:
self._modal_store.add_modal(modal, user_id)
def remove_view(self, view: View, message_id: Optional[int] = None) -> None:
self._view_store.remove_view(view, message_id)
def remove_modal(self, modal: Modal) -> None:
self._modal_store.remove_modal(modal)
def prevent_view_updates_for(self, message_id: Optional[int]) -> Optional[View]:
return self._view_store.remove_message_tracking(message_id) # type: ignore
def all_views(self) -> List[View]:
return self._view_store.all_views()
def views(self, persistent: bool = True) -> List[View]:
return self._view_store.views(persistent)
def guilds(self) -> List[Guild]:
return list(self._guilds.values())
def _get_guild(self, guild_id: Optional[int]) -> Optional[Guild]:
# the keys of self._guilds are ints
return self._guilds.get(guild_id) # type: ignore
def _add_guild(self, guild: Guild) -> None:
self._guilds[guild.id] = guild
def _remove_guild(self, guild: Guild) -> None:
self._guilds.pop(guild.id, None)
for emoji in guild.emojis:
self._emojis.pop(emoji.id, None)
for sticker in guild.stickers:
self._stickers.pop(sticker.id, None)
del guild
def emojis(self) -> List[Emoji]:
return list(self._emojis.values())
def stickers(self) -> List[GuildSticker]:
return list(self._stickers.values())
def get_emoji(self, emoji_id: Optional[int]) -> Optional[Emoji]:
# the keys of self._emojis are ints
return self._emojis.get(emoji_id) # type: ignore
def get_sticker(self, sticker_id: Optional[int]) -> Optional[GuildSticker]:
# the keys of self._stickers are ints
return self._stickers.get(sticker_id) # type: ignore
def private_channels(self) -> List[PrivateChannel]:
return list(self._private_channels.values())
def _get_private_channel(self, channel_id: Optional[int]) -> Optional[PrivateChannel]:
try:
# the keys of self._private_channels are ints
value = self._private_channels[channel_id] # type: ignore
except KeyError:
return None
else:
self._private_channels.move_to_end(channel_id) # type: ignore
return value
def _get_private_channel_by_user(self, user_id: Optional[int]) -> Optional[DMChannel]:
# the keys of self._private_channels are ints
return self._private_channels_by_user.get(user_id) # type: ignore
def _add_private_channel(self, channel: PrivateChannel) -> None:
channel_id = channel.id
self._private_channels[channel_id] = channel
if len(self._private_channels) > 128:
_, to_remove = self._private_channels.popitem(last=False)
if isinstance(to_remove, DMChannel) and to_remove.recipient:
self._private_channels_by_user.pop(to_remove.recipient.id, None)
if isinstance(channel, DMChannel) and channel.recipient:
self._private_channels_by_user[channel.recipient.id] = channel
def add_dm_channel(self, data: DMChannelPayload) -> DMChannel:
# self.user is *always* cached when this is called
channel = DMChannel(me=self.user, state=self, data=data) # type: ignore
self._add_private_channel(channel)
return channel
def _remove_private_channel(self, channel: PrivateChannel) -> None:
self._private_channels.pop(channel.id, None)
if isinstance(channel, DMChannel):
recipient = channel.recipient
if recipient is not None:
self._private_channels_by_user.pop(recipient.id, None)
def _get_message(self, msg_id: Optional[int]) -> Optional[Message]:
return (
utils.find(lambda m: m.id == msg_id, reversed(self._messages))
if self._messages
else None
)
def _add_guild_from_data(self, data: GuildPayload) -> Guild:
guild = Guild(data=data, state=self)
self._add_guild(guild)
return guild
def _guild_needs_chunking(self, guild: Guild) -> bool:
# If presences are enabled then we get back the old guild.large behaviour
return (
self._chunk_guilds
and not guild.chunked
and not (self._intents.presences and not guild.large)
)
def _get_guild_channel(
self, data: MessagePayload
) -> Tuple[Union[Channel, Thread], Optional[Guild]]:
channel_id = int(data["channel_id"])
try:
guild = self._get_guild(int(data["guild_id"]))
except KeyError:
channel = self.get_channel(channel_id)
if channel is None:
channel = DMChannel._from_message(self, channel_id)
guild = getattr(channel, "guild", None)
else:
channel = guild and guild._resolve_channel(channel_id)
return channel or PartialMessageable(state=self, id=channel_id), guild
def application_commands(self) -> Set[BaseApplicationCommand]:
"""Gets a copy of the ApplicationCommand object set. If the original is given out and modified, massive desyncs
may occur. This should be used internally as well if size-changed-during-iteration is a worry.
"""
return self._application_commands.copy()
def get_application_command(self, command_id: int) -> Optional[BaseApplicationCommand]:
return self._application_command_ids.get(command_id, None)
def get_application_command_from_signature(
self,
*,
type: int,
qualified_name: str,
guild_id: Optional[int],
search_localizations: bool = False,
) -> Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]]:
def get_parent_command(name: str, /) -> Optional[BaseApplicationCommand]:
found = self._application_command_signatures.get((name, type, guild_id))
if not search_localizations:
return found
for command in self._application_command_signatures.values():
if command.name_localizations and name in command.name_localizations.values():
found = command
break
return found
def find_children(
parent: Union[BaseApplicationCommand, SlashApplicationSubcommand], name: str, /
) -> Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]]:
children: Dict[str, SlashApplicationSubcommand] = getattr(parent, "children", {})
if not children:
return parent
found = children.get(name)
if not search_localizations:
return found
subcommand: Union[BaseApplicationCommand, SlashApplicationSubcommand]
for subcommand in children.values():
if subcommand.name_localizations and name in subcommand.name_localizations.values():
found = subcommand
break
return found
parent: Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]] = None
if not qualified_name:
return None
if " " not in qualified_name:
return get_parent_command(qualified_name)
for command_name in qualified_name.split(" "):
if parent is None:
parent = get_parent_command(command_name)
else:
parent = find_children(parent, command_name)
return parent
def get_guild_application_commands(
self, guild_id: Optional[int] = None, rollout: bool = False
) -> List[BaseApplicationCommand]:
"""Gets all commands that have the given guild ID. If guild_id is None, all guild commands are returned. if
rollout is True, guild_ids_to_rollout is used.
"""
return [
app_cmd
for app_cmd in self.application_commands
if guild_id is None
or guild_id in app_cmd.guild_ids
or (rollout and guild_id in app_cmd.guild_ids_to_rollout)
]
def get_global_application_commands(
self, rollout: bool = False
) -> List[BaseApplicationCommand]:
"""Gets all commands that are registered globally. If rollout is True, is_global is used."""
return [
app_cmd
for app_cmd in self.application_commands
if (rollout and app_cmd.is_global) or None in app_cmd.command_ids
]
def add_application_command(
self,
command: BaseApplicationCommand,
*,
overwrite: bool = False,
use_rollout: bool = False,
pre_remove: bool = True,
) -> None:
"""Adds the command to the state and updates the state with any changes made to the command.
Removes all existing references, then adds them.
Safe to call multiple times on the same application command.
Parameters
----------
command: :class:`BaseApplicationCommand`
The command to add/update the state with.
overwrite: :class:`bool`
If the library will let you add a command that overlaps with an existing command. Default ``False``.
use_rollout: :class:`bool`
If the command should be added to the state with its rollout guild IDs.
pre_remove: :class:`bool`
If the command should be removed before adding it. This will clear all signatures from storage, including
rollout ones.
"""
if pre_remove:
self.remove_application_command(command)
signature_set = (
command.get_rollout_signatures() if use_rollout else command.get_signatures()
)
for signature in signature_set:
if not overwrite and (
found_command := self._application_command_signatures.get(signature, None)
):
if found_command is not command:
raise ValueError(
f"{command.error_name} You cannot add application commands with duplicate "
f"signatures."
)
# No else because we do not care if the command has its own signature already in.
else:
self._application_command_signatures[signature] = command
for command_id in command.command_ids.values():
# PyCharm flags found_command as it "might be referenced before assignment", but that can't happen due to it
# being in an AND statement.
# noinspection PyUnboundLocalVariable
if (
not overwrite
and (found_command := self._application_command_ids.get(command_id, None))
and found_command is not command
):
raise ValueError(
f"{command.error_name} You cannot add application commands with duplicate IDs."
)
self._application_command_ids[command_id] = command
# TODO: Add the command to guilds. Should it? Check if it does in the Guild add.
self._application_commands.add(command)
def remove_application_command(self, command: BaseApplicationCommand) -> None:
"""Removes the command and all signatures + associated IDs from the state.
Safe to call with commands that aren't in the state.
Parameters
----------
command: :class:`BaseApplicationCommand`
the command to remove from the state.
"""
signature_set = command.get_rollout_signatures()
for signature in signature_set:
self._application_command_signatures.pop(signature, None)
for cmd_id in command.command_ids.values():
self._application_command_ids.pop(cmd_id, None)
self._application_commands.discard(command)
def add_all_rollout_signatures(self) -> None:
"""This adds all command signatures for rollouts to the signature cache."""
for command in self._application_commands:
self.add_application_command(command, use_rollout=True)
async def sync_all_application_commands(
self,
data: Optional[Dict[Optional[int], List[ApplicationCommandPayload]]] = None,
*,
use_rollout: bool = True,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
ignore_forbidden: bool = True,
):
"""|coro|
Syncs all application commands with Discord. Will sync global commands if any commands added are global, and
syncs with all guilds that have an application command targeting them.
This may call Discord many times depending on how different guilds you have local commands for, and how many
commands Discord needs to be updated or added, which may cause your bot to be rate limited or even Cloudflare
banned in VERY extreme cases.
This may incur high CPU usage depending on how many commands you have and how complex they are, which may cause
your bot to halt while it checks local commands against the existing commands that Discord has.
For a more targeted version of this method, see :func:`Client.sync_application_commands`
Parameters
----------
data: Optional[Dict[Optional[:class:`int`], List[:class:`dict`]]]
Data to use when comparing local application commands to what Discord has. The key should be the
:class:`int` guild ID (`None` for global) corresponding to the value list of application command payloads
from Discord. Any guild ID's not provided will be fetched if needed. Defaults to ``None``
use_rollout: :class:`bool`
If the rollout guild IDs of commands should be used. Defaults to ``True``
associate_known: :class:`bool`
If local commands that match a command already on Discord should be associated with each other.
Defaults to ``True``
delete_unknown: :class:`bool`
If commands on Discord that don't match a local command should be deleted. Defaults to ``True``.
update_known: :class:`bool`
If commands on Discord have a basic match with a local command, but don't fully match, should be updated.
Defaults to ``True``
register_new: :class:`bool`
If a local command that doesn't have a basic match on Discord should be added to Discord.
Defaults to ``True``
ignore_forbidden: :class:`bool`
If this command should raise an :class:`errors.Forbidden` exception when the bot encounters a guild where
it doesn't have permissions to view application commands.
Defaults to ``True``
"""
_log.debug("Beginning sync of all application commands.")
self._get_client().add_all_application_commands()
data = {} if data is None else data.copy()
if self.application_id is None:
raise TypeError("Could not get the current application's id")
for app_cmd in self.application_commands:
self.add_application_command(command=app_cmd, use_rollout=use_rollout)
if app_cmd.is_global and None not in data:
data[None] = await self.http.get_global_commands(self.application_id)
_log.debug("Fetched global application command data.")
if app_cmd.is_guild:
for guild_id in app_cmd.guild_ids_to_rollout if use_rollout else app_cmd.guild_ids:
if guild_id not in data:
try:
data[guild_id] = await self.http.get_guild_commands(
self.application_id, guild_id
)
_log.debug(
"Fetched guild application command data for guild ID %s", guild_id
)
except Forbidden as e:
if ignore_forbidden:
_log.warning(
"nextcord.Client: Forbidden error for %s, is the applications.commands "
"Oauth scope enabled? %s",
guild_id,
e,
)
else:
raise e
for guild_id in data:
_log.debug("Running sync for %s", "global" if guild_id is None else f"Guild {guild_id}")
await self.sync_application_commands(
data=data[guild_id],
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
register_new=register_new,
)
async def sync_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
) -> None:
"""|coro|
Syncs the locally added application commands with the Guild corresponding to the given ID, or syncs
global commands if the guild_id is ``None``.
Parameters
----------
data: Optional[List[:class:`dict`]]
Data to use when comparing local application commands to what Discord has. Should be a list of application
command data from Discord. If left as ``None``, it will be fetched if needed. Defaults to ``None``.
guild_id: Optional[:class:`int`]
ID of the guild to sync application commands with. If set to ``None``, global commands will be synced instead.
Defaults to ``None``.
associate_known: :class:`bool`
If local commands that match a command already on Discord should be associated with each other.
Defaults to ``True``.
delete_unknown: :class:`bool`
If commands on Discord that don't match a local command should be deleted. Defaults to ``True``.
update_known: :class:`bool`
If commands on Discord have a basic match with a local command, but don't fully match, should be updated.
Defaults to ``True``.
register_new: :class:`bool`
If a local command that doesn't have a basic match on Discord should be added to Discord.
Defaults to ``True``.
"""
_log.debug("Syncing commands to %s", guild_id)
if self.application_id is None:
raise TypeError("Could not get the current application's id")
if not data:
if guild_id:
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
await self.discover_application_commands(
data=data,
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
if register_new:
await self.register_new_application_commands(data=data, guild_id=guild_id)
_log.debug("Command sync with Guild %s finished.", guild_id)
async def discover_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
) -> None:
"""|coro|
Associates existing, deletes unknown, and updates modified commands for either global commands or a specific
guild. This does a deep check on found commands, which may be expensive CPU-wise.
Running this for global or the same guild multiple times at once may cause unexpected or unstable behavior.
Parameters
----------
data: Optional[List[:class:`dict]]
Payload from ``HTTPClient.get_guild_commands`` or ``HTTPClient.get_global_commands`` to deploy with. If None,
the payload will be retrieved from Discord.
guild_id: Optional[:class:`int`]
Guild ID to deploy application commands to. If ``None``, global commands are deployed to.
associate_known: :class:`bool`
If True, commands on Discord that pass a signature check and a deep check will be associated with locally
added ApplicationCommand objects.
delete_unknown: :class:`bool`
If ``True``, commands on Discord that fail a signature check will be removed. If ``update_known`` is False,
commands that pass the signature check but fail the deep check will also be removed.
update_known: :class:`bool`
If ``True``, commands on Discord that pass a signature check but fail the deep check will be updated.
"""
if not associate_known and not delete_unknown and not update_known:
# If everything is disabled, there is no point in doing anything.
return
if self.application_id is None:
raise NotImplementedError("Could not get the current application id")
if not data:
if guild_id:
# we do not care about typeddict specificity here
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
for raw_response in data:
payload_type = raw_response["type"] if "type" in raw_response else 1
fixed_guild_id = raw_response.get("guild_id", None)
response_signature = {
"type": int(payload_type),
"qualified_name": raw_response["name"],
"guild_id": None if not fixed_guild_id else int(fixed_guild_id),
}
app_cmd = self.get_application_command_from_signature(**response_signature)
if app_cmd:
if not isinstance(app_cmd, BaseApplicationCommand):
raise ValueError(
(
f".get_application_command_from_signature with kwargs: {response_signature} "
f"returned {type(app_cmd)} but BaseApplicationCommand was expected."
)
)
if app_cmd.is_payload_valid(raw_response, guild_id):
if associate_known:
_log.debug(
"nextcord.ConnectionState: Command with signature %s associated with added command.",
response_signature,
)
app_cmd.parse_discord_response(self, raw_response)
self.add_application_command(app_cmd, use_rollout=True)
elif update_known:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, updating.",
response_signature,
)
await self.register_application_command(app_cmd, guild_id)
elif delete_unknown:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, removing.",
response_signature,
)
# TODO: Re-examine how worthwhile this is.
await self.delete_application_command(app_cmd, guild_id)
elif delete_unknown:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, removing.",
response_signature,
)
if guild_id:
await self.http.delete_guild_command(
self.application_id, guild_id, raw_response["id"]
)
else:
await self.http.delete_global_command(self.application_id, raw_response["id"])
async def deploy_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
*,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
) -> None:
warnings.warn(
".deploy_application_commands is deprecated, use .discover_application_commands instead.",
stacklevel=2,
category=FutureWarning,
)
await self.discover_application_commands(
data=data,
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
async def associate_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".associate_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=True,
delete_unknown=False,
update_known=False,
)
async def delete_unknown_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".delete_unknown_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=False,
delete_unknown=True,
update_known=False,
)
async def update_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".update_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=False,
delete_unknown=False,
update_known=True,
)
async def register_new_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
"""|coro|
Registers locally added application commands that don't match a signature that Discord has registered for
either global commands or a specific guild.
Parameters
----------
data: Optional[List[:class:`dict`]]
Data to use when comparing local application commands to what Discord has. Should be a list of application
command data from Discord. If left as ``None``, it will be fetched if needed. Defaults to ``None``
guild_id: Optional[:class:`int`]
ID of the guild to sync application commands with. If set to ``None``, global commands will be synced instead.
Defaults to ``None``.
"""
if not data:
if self.application_id is None:
raise TypeError("Could not get the current application id")
if guild_id:
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
data_signatures = [
(
raw_response["name"],
int(raw_response["type"] if "type" in raw_response else 1),
int(temp) if (temp := raw_response.get("guild_id", None)) else temp,
)
for raw_response in data
]
# add_application_command can change the size of the dictionary, and apparently .items() doesn't prevent that
# "RuntimeError: dictionary changed size during iteration" from happening. So a copy is made for just this.
for signature, app_cmd in self._application_command_signatures.copy().items():
if (
signature not in data_signatures and signature[2] == guild_id
): # index 2 of the tuple is the guild ID.
await self.register_application_command(app_cmd, guild_id)
async def register_application_command(
self, command: BaseApplicationCommand, guild_id: Optional[int] = None
) -> None:
"""|coro|
Registers the given application command either for a specific guild or globally and adds the command to the bot.
Parameters
----------
command: :class:`BaseApplicationCommand`
Application command to register.
guild_id: Optional[:class:`int`]
ID of the guild to register the application commands to. If set to ``None``, the commands will be registered
as global commands instead. Defaults to ``None``.
"""
payload: EditApplicationCommand = command.get_payload(guild_id) # type: ignore
_log.info(
"nextcord.ConnectionState: Registering command with signature %s",
command.get_signature(guild_id),
)
if self.application_id is None:
raise TypeError("Could not get the current application's id")
try:
if guild_id:
raw_response = await self.http.upsert_guild_command(
self.application_id, guild_id, payload
)
else:
raw_response = await self.http.upsert_global_command(self.application_id, payload)
except Exception as e:
_log.error("Error registering command %s: %s", command.error_name, e)
raise e
command.parse_discord_response(self, raw_response)
self.add_application_command(command, pre_remove=False)
async def delete_application_command(
self, command: BaseApplicationCommand, guild_id: Optional[int] = None
) -> None:
"""|coro|
Deletes the given application from Discord for the given guild ID or globally, then removes the signature and
command ID from the cache if possible.
Parameters
----------
command: :class:`ApplicationCommand`
Application command to delete.
guild_id: Optional[:class:`int`]
Guild ID to delete the application commands from. If ``None``, the command is deleted from global.
"""
if self.application_id is None:
raise NotImplementedError("Could not get the current application id")
try:
if guild_id:
await self.http.delete_guild_command(
self.application_id, guild_id, command.command_ids[guild_id]
)
else:
await self.http.delete_global_command(
self.application_id, command.command_ids[guild_id]
)
self._application_command_ids.pop(command.command_ids[guild_id], None)
self._application_command_signatures.pop(command.get_signature(guild_id), None)
except KeyError as e:
if guild_id:
_log.error(
"Could not globally unregister command %s "
"as it is not registered in the provided guild.",
command.error_name,
)
raise KeyError(
"This command cannot be globally unregistered, "
"as it is not registered in the provided guild."
) from e
_log.error(
"Could not globally unregister command %s as it is not a global command.",
command.error_name,
)
raise KeyError(
"This command cannot be globally unregistered, as it is not a global command."
) from e
except Exception as e:
_log.error("Error unregistering command %s: %s", command.error_name, e)
raise e
# async def register_bulk_application_commands(self) -> None:
# # TODO: Using Bulk upsert seems to delete all commands
# # It might be good to keep this around as a reminder for future work. Bulk upsert seem to delete everything
# # that isn't part of that bulk upsert, for both global and guild commands. While useful, this will
# # update/overwrite existing commands, which may (needs testing) wipe out all permissions associated with those
# # commands. Look for an opportunity to use bulk upsert.
# raise NotImplementedError
async def chunker(
self,
guild_id: int,
query: str = "",
limit: int = 0,
presences: bool = False,
*,
nonce: Optional[str] = None,
) -> None:
ws = self._get_websocket(guild_id) # This is ignored upstream
await ws.request_chunks(
guild_id, query=query, limit=limit, presences=presences, nonce=nonce
)
async def query_members(
self,
guild: Guild,
query: Optional[str],
limit: int,
user_ids: Optional[List[int]],
cache: bool,
presences: bool,
) -> List[Member]:
guild_id = guild.id
ws = self._get_websocket(guild_id)
if ws is None: # pyright: ignore[reportUnnecessaryComparison]
raise RuntimeError("Somehow do not have a websocket for this guild_id")
request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache)
self._chunk_requests[request.nonce] = request
try:
# start the query operation
await ws.request_chunks(
guild_id,
query=query,
limit=limit,
user_ids=user_ids,
presences=presences,
nonce=request.nonce,
)
return await asyncio.wait_for(request.wait(), timeout=30.0)
except asyncio.TimeoutError:
_log.warning(
"Timed out waiting for chunks with query %r and limit %d for guild_id %d",
query,
limit,
guild_id,
)
raise
async def _delay_ready(self) -> None:
try:
states = []
while True:
# this snippet of code is basically waiting N seconds
# until the last GUILD_CREATE was sent
try:
guild = await asyncio.wait_for(
self._ready_state.get(), timeout=self.guild_ready_timeout
)
except asyncio.TimeoutError:
break
else:
if self._guild_needs_chunking(guild):
future = await self.chunk_guild(guild, wait=False)
states.append((guild, future))
elif guild.unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
for guild, future in states:
try:
await asyncio.wait_for(future, timeout=5.0)
except asyncio.TimeoutError:
_log.warning(
"Shard ID %s timed out waiting for chunks for guild_id %s.",
guild.shard_id,
guild.id,
)
if guild.unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
# remove the state
# AttributeError: already been deleted somehow
with contextlib.suppress(AttributeError):
del self._ready_state
except asyncio.CancelledError:
pass
else:
# dispatch the event
self.call_handlers("ready")
self.dispatch("ready")
finally:
self._ready_task = None
def parse_ready(self, data) -> None:
if self._ready_task is not None:
self._ready_task.cancel()
self._ready_state = asyncio.Queue()
self.clear(views=False)
self.user = ClientUser(state=self, data=data["user"])
self.store_user(data["user"])
if self.application_id is None:
try:
application = data["application"]
except KeyError:
pass
else:
self.application_id = utils.get_as_snowflake(application, "id")
# flags will always be present here
self.application_flags = ApplicationFlags._from_value(application["flags"])
for guild_data in data["guilds"]:
self._add_guild_from_data(guild_data)
self.dispatch("connect")
self._ready_task = asyncio.create_task(self._delay_ready())
def parse_resumed(self, data) -> None:
self.dispatch("resumed")
def parse_message_create(self, data) -> None:
channel, _ = self._get_guild_channel(data)
# channel would be the correct type here
message = Message(channel=channel, data=data, state=self) # type: ignore
self.dispatch("message", message)
if self._messages is not None:
self._messages.append(message)
# we ensure that the channel is either a TextChannel, ForumChannel, Thread or VoiceChannel
if channel and channel.__class__ in (TextChannel, ForumChannel, Thread, VoiceChannel):
channel.last_message_id = message.id # type: ignore
def parse_message_delete(self, data) -> None:
raw = RawMessageDeleteEvent(data)
found = self._get_message(raw.message_id)
raw.cached_message = found
self.dispatch("raw_message_delete", raw)
if self._messages is not None and found is not None:
self.dispatch("message_delete", found)
self._messages.remove(found)
def parse_message_delete_bulk(self, data) -> None:
raw = RawBulkMessageDeleteEvent(data)
if self._messages:
found_messages = [
message for message in self._messages if message.id in raw.message_ids
]
else:
found_messages = []
raw.cached_messages = found_messages
self.dispatch("raw_bulk_message_delete", raw)
if found_messages:
self.dispatch("bulk_message_delete", found_messages)
for msg in found_messages:
# self._messages won't be None here
self._messages.remove(msg) # type: ignore
def parse_message_update(self, data) -> None:
raw = RawMessageUpdateEvent(data)
message = self._get_message(raw.message_id)
if message is not None:
older_message = copy.copy(message)
raw.cached_message = older_message
self.dispatch("raw_message_edit", raw)
message._update(data)
# Coerce the `after` parameter to take the new updated Member
# ref: #5999
older_message.author = message.author
self.dispatch("message_edit", older_message, message)
else:
self.dispatch("raw_message_edit", raw)
if "components" in data and self._view_store.is_message_tracked(raw.message_id):
self._view_store.update_from_message(raw.message_id, data["components"])
def parse_message_reaction_add(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(
self, id=emoji_id, animated=emoji.get("animated", False), name=emoji["name"]
)
raw = RawReactionActionEvent(data, emoji, "REACTION_ADD")
member_data = data.get("member")
if member_data:
guild = self._get_guild(raw.guild_id)
if guild is not None:
raw.member = Member(data=member_data, guild=guild, state=self)
else:
raw.member = None
else:
raw.member = None
self.dispatch("raw_reaction_add", raw)
# rich interface here
message = self._get_message(raw.message_id)
if message is not None:
emoji = self._upgrade_partial_emoji(emoji)
reaction = message._add_reaction(data, emoji, raw.user_id)
user = raw.member or self._get_reaction_user(message.channel, raw.user_id)
if user:
self.dispatch("reaction_add", reaction, user)
def parse_message_reaction_remove_all(self, data) -> None:
raw = RawReactionClearEvent(data)
self.dispatch("raw_reaction_clear", raw)
message = self._get_message(raw.message_id)
if message is not None:
old_reactions = message.reactions.copy()
message.reactions.clear()
self.dispatch("reaction_clear", message, old_reactions)
def parse_message_reaction_remove(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji["name"])
raw = RawReactionActionEvent(data, emoji, "REACTION_REMOVE")
self.dispatch("raw_reaction_remove", raw)
message = self._get_message(raw.message_id)
if message is not None:
emoji = self._upgrade_partial_emoji(emoji)
try:
reaction = message._remove_reaction(data, emoji, raw.user_id)
except (AttributeError, ValueError): # eventual consistency lol
pass
else:
user = self._get_reaction_user(message.channel, raw.user_id)
if user:
self.dispatch("reaction_remove", reaction, user)
def parse_message_reaction_remove_emoji(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji["name"])
raw = RawReactionClearEmojiEvent(data, emoji)
self.dispatch("raw_reaction_clear_emoji", raw)
message = self._get_message(raw.message_id)
if message is not None:
try:
reaction = message._clear_emoji(emoji)
except (AttributeError, ValueError): # eventual consistency lol
pass
else:
if reaction:
self.dispatch("reaction_clear_emoji", reaction)
def parse_interaction_create(self, data) -> None:
interaction = self._get_client().get_interaction(data=data)
if data["type"] == 3: # interaction component
custom_id = interaction.data["custom_id"] # type: ignore
component_type = interaction.data["component_type"] # type: ignore
self._view_store.dispatch(component_type, custom_id, interaction)
if data["type"] == 5: # modal submit
custom_id = interaction.data["custom_id"] # type: ignore
# key exists if type is 5 etc
self._modal_store.dispatch(custom_id, interaction)
self.dispatch("interaction", interaction)
def parse_presence_update(self, data) -> None:
guild_id = utils.get_as_snowflake(data, "guild_id")
# guild_id won't be None here
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("PRESENCE_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id)
return
user = data["user"]
member_id = int(user["id"])
member = guild.get_member(member_id)
if member is None:
_log.debug(
"PRESENCE_UPDATE referencing an unknown member ID: %s. Discarding", member_id
)
return
old_member = Member._copy(member)
user_update = member._presence_update(data=data, user=user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
self.dispatch("presence_update", old_member, member)
def parse_user_update(self, data) -> None:
# self.user is *always* cached when this is called
user: ClientUser = self.user # type: ignore
user._update(data)
ref = self._users.get(user.id)
if ref:
ref._update(data)
def parse_invite_create(self, data) -> None:
invite = Invite.from_gateway(state=self, data=data)
self.dispatch("invite_create", invite)
def parse_invite_delete(self, data) -> None:
invite = Invite.from_gateway(state=self, data=data)
self.dispatch("invite_delete", invite)
def parse_channel_delete(self, data) -> None:
guild = self._get_guild(utils.get_as_snowflake(data, "guild_id"))
channel_id = int(data["id"])
if guild is not None:
channel = guild.get_channel(channel_id)
if channel is not None:
guild._remove_channel(channel)
self.dispatch("guild_channel_delete", channel)
def parse_channel_update(self, data) -> None:
channel_type = try_enum(ChannelType, data.get("type"))
channel_id = int(data["id"])
if channel_type is ChannelType.group:
channel = self._get_private_channel(channel_id)
old_channel = copy.copy(channel)
# the channel is a GroupChannel
channel._update_group(data) # type: ignore
self.dispatch("private_channel_update", old_channel, channel)
return
guild_id = utils.get_as_snowflake(data, "guild_id")
guild = self._get_guild(guild_id)
if guild is not None:
channel = guild.get_channel(channel_id)
if channel is not None:
old_channel = copy.copy(channel)
channel._update(guild, data)
self.dispatch("guild_channel_update", old_channel, channel)
else:
_log.debug(
"CHANNEL_UPDATE referencing an unknown channel ID: %s. Discarding.", channel_id
)
else:
_log.debug("CHANNEL_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id)
def parse_channel_create(self, data) -> None:
factory, _ = _channel_factory(data["type"])
if factory is None:
_log.debug(
"CHANNEL_CREATE referencing an unknown channel type %s. Discarding.", data["type"]
)
return
guild_id = utils.get_as_snowflake(data, "guild_id")
guild = self._get_guild(guild_id)
if guild is not None:
# the factory can't be a DMChannel or GroupChannel here
channel = factory(guild=guild, state=self, data=data) # type: ignore
guild._add_channel(channel) # type: ignore
self.dispatch("guild_channel_create", channel)
else:
_log.debug("CHANNEL_CREATE referencing an unknown guild ID: %s. Discarding.", guild_id)
return
def parse_channel_pins_update(self, data) -> None:
channel_id = int(data["channel_id"])
try:
guild = self._get_guild(int(data["guild_id"]))
except KeyError:
guild = None
channel = self._get_private_channel(channel_id)
else:
channel = guild and guild._resolve_channel(channel_id)
if channel is None:
_log.debug(
"CHANNEL_PINS_UPDATE referencing an unknown channel ID: %s. Discarding.", channel_id
)
return
last_pin = (
utils.parse_time(data["last_pin_timestamp"]) if data["last_pin_timestamp"] else None
)
if guild is None:
self.dispatch("private_channel_pins_update", channel, last_pin)
else:
self.dispatch("guild_channel_pins_update", channel, last_pin)
def parse_thread_create(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_CREATE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread = Thread(guild=guild, state=guild._state, data=data)
has_thread = guild.get_thread(thread.id)
guild._add_thread(thread)
if not has_thread:
# `newly_created` is documented outside of a thread's fields:
# https://discord.dev/topics/gateway-events#thread-create
if data.get("newly_created", False):
if isinstance(thread.parent, ForumChannel):
thread.parent.last_message_id = thread.id
self.dispatch("thread_create", thread)
# Avoid an unnecessary breaking change right now by dispatching `thread_join` for
# threads that were already created.
self.dispatch("thread_join", thread)
def parse_thread_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread_id = int(data["id"])
thread = guild.get_thread(thread_id)
if thread is not None:
old = copy.copy(thread)
thread._update(data)
self.dispatch("thread_update", old, thread)
else:
thread = Thread(guild=guild, state=guild._state, data=data)
guild._add_thread(thread)
self.dispatch("thread_join", thread)
def parse_thread_delete(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_DELETE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread_id = int(data["id"])
thread = guild.get_thread(thread_id)
if thread is not None:
guild._remove_thread(thread)
self.dispatch("thread_delete", thread)
def parse_thread_list_sync(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_LIST_SYNC referencing an unknown guild ID: %s. Discarding", guild_id)
return
try:
channel_ids = set(data["channel_ids"])
except KeyError:
# If not provided, then the entire guild is being synced
# So all previous thread data should be overwritten
previous_threads = guild._threads.copy()
guild._clear_threads()
else:
previous_threads = guild._filter_threads(channel_ids)
threads = {d["id"]: guild._store_thread(d) for d in data.get("threads", [])}
for member in data.get("members", []):
try:
# note: member['id'] is the thread_id
thread = threads[member["id"]]
except KeyError:
continue
else:
thread._add_member(ThreadMember(thread, member))
for thread in threads.values():
old = previous_threads.pop(thread.id, None)
if old is None:
self.dispatch("thread_join", thread)
for thread in previous_threads.values():
self.dispatch("thread_remove", thread)
def parse_thread_member_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug(
"THREAD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id
)
return
thread_id = int(data["id"])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
_log.debug(
"THREAD_MEMBER_UPDATE referencing an unknown thread ID: %s. Discarding", thread_id
)
return
member = ThreadMember(thread, data)
thread.me = member
def parse_thread_members_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug(
"THREAD_MEMBERS_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id
)
return
thread_id = int(data["id"])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
_log.debug(
"THREAD_MEMBERS_UPDATE referencing an unknown thread ID: %s. Discarding", thread_id
)
return
added_members = [ThreadMember(thread, d) for d in data.get("added_members", [])]
removed_member_ids = [int(x) for x in data.get("removed_member_ids", [])]
self_id = self.self_id
for member in added_members:
if member.id != self_id:
thread._add_member(member)
self.dispatch("thread_member_join", member)
else:
thread.me = member
self.dispatch("thread_join", thread)
for member_id in removed_member_ids:
if member_id != self_id:
member = thread._pop_member(member_id)
if member is not None:
self.dispatch("thread_member_remove", member)
else:
self.dispatch("thread_remove", thread)
def parse_guild_member_add(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_MEMBER_ADD referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
member = Member(guild=guild, data=data, state=self)
if self.member_cache_flags.joined:
guild._add_member(member)
with contextlib.suppress(AttributeError):
guild._member_count += 1
self.dispatch("member_join", member)
def parse_guild_member_remove(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
with contextlib.suppress(AttributeError):
guild._member_count -= 1
user_id = int(data["user"]["id"])
member = guild.get_member(user_id)
if member is not None:
guild._remove_member(member)
self.dispatch("member_remove", member)
else:
_log.debug(
(
"GUILD_MEMBER_REMOVE referencing an unknown guild ID: %s."
"Falling back to raw data."
),
data["guild_id"],
)
raw = RawMemberRemoveEvent(data=data, state=self)
self.dispatch("raw_member_remove", raw)
def parse_guild_member_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
user = data["user"]
user_id = int(user["id"])
if guild is None:
_log.debug(
"GUILD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
member = guild.get_member(user_id)
if member is not None:
old_member = Member._copy(member)
member._update(data)
user_update = member._update_inner_user(user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
self.dispatch("member_update", old_member, member)
else:
if self.member_cache_flags.joined:
member = Member(data=data, guild=guild, state=self)
# Force an update on the inner user if necessary
user_update = member._update_inner_user(user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
guild._add_member(member)
_log.debug(
"GUILD_MEMBER_UPDATE referencing an unknown member ID: %s. Discarding.", user_id
)
def parse_guild_emojis_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_EMOJIS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
before_emojis = guild.emojis
for emoji in before_emojis:
self._emojis.pop(emoji.id, None)
guild.emojis = tuple([self.store_emoji(guild, d) for d in data["emojis"]])
self.dispatch("guild_emojis_update", guild, before_emojis, guild.emojis)
def parse_guild_stickers_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_STICKERS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
before_stickers = guild.stickers
for emoji in before_stickers:
self._stickers.pop(emoji.id, None)
guild.stickers = tuple([self.store_sticker(guild, d) for d in data["stickers"]])
self.dispatch("guild_stickers_update", guild, before_stickers, guild.stickers)
def _get_create_guild(self, data):
if data.get("unavailable") is False:
# GUILD_CREATE with unavailable in the response
# usually means that the guild has become available
# and is therefore in the cache
guild = self._get_guild(int(data["id"]))
if guild is not None:
guild.unavailable = False
guild._from_data(data)
return guild
return self._add_guild_from_data(data)
def is_guild_evicted(self, guild) -> bool:
return guild.id not in self._guilds
async def chunk_guild(self, guild, *, wait: bool = True, cache=None):
if cache is None:
cache = self.member_cache_flags.joined
request = self._chunk_requests.get(guild.id)
if request is None:
self._chunk_requests[guild.id] = request = ChunkRequest(
guild.id, self.loop, self._get_guild, cache=cache
)
await self.chunker(guild.id, nonce=request.nonce)
if wait:
return await request.wait()
return request.get_future()
async def _chunk_and_dispatch(self, guild, unavailable) -> None:
try:
await asyncio.wait_for(self.chunk_guild(guild), timeout=60.0)
except asyncio.TimeoutError:
_log.info("Somehow timed out waiting for chunks.")
if unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
def parse_guild_create(self, data) -> None:
unavailable = data.get("unavailable")
if unavailable is True:
# joined a guild with unavailable == True so..
return
guild = self._get_create_guild(data)
try:
# Notify the on_ready state, if any, that this guild is complete.
self._ready_state.put_nowait(guild)
except AttributeError:
pass
else:
# If we're waiting for the event, put the rest on hold
return
# check if it requires chunking
if self._guild_needs_chunking(guild):
task = asyncio.create_task(self._chunk_and_dispatch(guild, unavailable))
self._chunk_tasks[guild.id] = task
task.add_done_callback(lambda _t: self._chunk_tasks.pop(guild.id, None))
return
# Dispatch available if newly available
if unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
def parse_guild_update(self, data) -> None:
guild = self._get_guild(int(data["id"]))
if guild is not None:
old_guild = copy.copy(guild)
guild._from_data(data)
self.dispatch("guild_update", old_guild, guild)
else:
_log.debug("GUILD_UPDATE referencing an unknown guild ID: %s. Discarding.", data["id"])
def parse_guild_delete(self, data) -> None:
guild = self._get_guild(int(data["id"]))
if guild is None:
_log.debug("GUILD_DELETE referencing an unknown guild ID: %s. Discarding.", data["id"])
return
if data.get("unavailable", False):
# GUILD_DELETE with unavailable being True means that the
# guild that was available is now currently unavailable
guild.unavailable = True
self.dispatch("guild_unavailable", guild)
return
# do a cleanup of the messages cache
if self._messages is not None:
self._messages: Optional[Deque[Message]] = deque(
(msg for msg in self._messages if msg.guild != guild), maxlen=self.max_messages
)
self._remove_guild(guild)
self.dispatch("guild_remove", guild)
def parse_guild_ban_add(self, data) -> None:
# we make the assumption that GUILD_BAN_ADD is done
# before GUILD_MEMBER_REMOVE is called
# hence we don't remove it from cache or do anything
# strange with it, the main purpose of this event
# is mainly to dispatch to another event worth listening to for logging
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
try:
user = User(data=data["user"], state=self)
except KeyError:
pass
else:
member = guild.get_member(user.id) or user
self.dispatch("member_ban", guild, member)
def parse_guild_ban_remove(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None and "user" in data:
user = self.store_user(data["user"])
self.dispatch("member_unban", guild, user)
def parse_guild_role_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_ROLE_CREATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
role_data = data["role"]
role = Role(guild=guild, data=role_data, state=self)
guild._add_role(role)
self.dispatch("guild_role_create", role)
def parse_guild_role_delete(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
role_id = int(data["role_id"])
try:
role = guild._remove_role(role_id)
except KeyError:
return
else:
self.dispatch("guild_role_delete", role)
else:
_log.debug(
"GUILD_ROLE_DELETE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_role_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
role_data = data["role"]
role_id = int(role_data["id"])
role = guild.get_role(role_id)
if role is not None:
old_role = copy.copy(role)
role._update(role_data)
self.dispatch("guild_role_update", old_role, role)
else:
_log.debug(
"GUILD_ROLE_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_members_chunk(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
presences = data.get("presences", [])
# the guild won't be None here
members = [Member(guild=guild, data=member, state=self) for member in data.get("members", [])] # type: ignore
_log.debug("Processed a chunk for %s members in guild ID %s.", len(members), guild_id)
if presences:
member_dict = {str(member.id): member for member in members}
for presence in presences:
user = presence["user"]
member_id = user["id"]
member = member_dict.get(member_id)
if member is not None:
member._presence_update(presence, user)
complete = data.get("chunk_index", 0) + 1 == data.get("chunk_count")
self.process_chunk_requests(guild_id, data.get("nonce"), members, complete)
def parse_guild_integrations_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
self.dispatch("guild_integrations_update", guild)
else:
_log.debug(
"GUILD_INTEGRATIONS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_integration_create(self, data) -> None:
guild_id = int(data.pop("guild_id"))
guild = self._get_guild(guild_id)
if guild is not None:
cls, _ = _integration_factory(data["type"])
integration = cls(data=data, guild=guild)
self.dispatch("integration_create", integration)
else:
_log.debug(
"INTEGRATION_CREATE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_integration_update(self, data) -> None:
guild_id = int(data.pop("guild_id"))
guild = self._get_guild(guild_id)
if guild is not None:
cls, _ = _integration_factory(data["type"])
integration = cls(data=data, guild=guild)
self.dispatch("integration_update", integration)
else:
_log.debug(
"INTEGRATION_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_integration_delete(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is not None:
raw = RawIntegrationDeleteEvent(data)
self.dispatch("raw_integration_delete", raw)
else:
_log.debug(
"INTEGRATION_DELETE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_webhooks_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"WEBHOOKS_UPDATE referencing an unknown guild ID: %s. Discarding", data["guild_id"]
)
return
channel = guild.get_channel(int(data["channel_id"]))
if channel is not None:
self.dispatch("webhooks_update", channel)
else:
_log.debug(
"WEBHOOKS_UPDATE referencing an unknown channel ID: %s. Discarding.",
data["channel_id"],
)
def parse_stage_instance_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
stage_instance = StageInstance(guild=guild, state=self, data=data)
guild._stage_instances[stage_instance.id] = stage_instance
self.dispatch("stage_instance_create", stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_CREATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_stage_instance_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
stage_instance = guild._stage_instances.get(int(data["id"]))
if stage_instance is not None:
old_stage_instance = copy.copy(stage_instance)
stage_instance._update(data)
self.dispatch("stage_instance_update", old_stage_instance, stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_UPDATE referencing unknown stage instance ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"STAGE_INSTANCE_UPDATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_stage_instance_delete(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
try:
stage_instance = guild._stage_instances.pop(int(data["id"]))
except KeyError:
pass
else:
self.dispatch("stage_instance_delete", stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_DELETE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_voice_state_update(self, data) -> None:
guild = self._get_guild(utils.get_as_snowflake(data, "guild_id"))
channel_id = utils.get_as_snowflake(data, "channel_id")
flags = self.member_cache_flags
# self.user is *always* cached when this is called
self_id = self.user.id # type: ignore
if guild is not None:
if int(data["user_id"]) == self_id:
voice = self._get_voice_client(guild.id)
if voice is not None:
coro = voice.on_voice_state_update(data)
task = asyncio.create_task(
logging_coroutine(coro, info="Voice Protocol voice state update handler")
)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
member, before, after = guild._update_voice_state(data, channel_id) # type: ignore
after = copy.copy(after)
if member is not None:
if flags.voice:
if channel_id is None and flags._voice_only and member.id != self_id:
# Only remove from cache if we only have the voice flag enabled
# Member doesn't meet the Snowflake protocol currently
guild._remove_member(member)
elif channel_id is not None:
guild._add_member(member)
self.dispatch("voice_state_update", member, before, after)
else:
_log.debug(
"VOICE_STATE_UPDATE referencing an unknown member ID: %s. Discarding.",
data["user_id"],
)
def parse_voice_server_update(self, data) -> None:
try:
key_id = int(data["guild_id"])
except KeyError:
key_id = int(data["channel_id"])
vc = self._get_voice_client(key_id)
if vc is not None:
coro = vc.on_voice_server_update(data)
task = asyncio.create_task(
logging_coroutine(coro, info="Voice Protocol voice server update handler")
)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
def parse_typing_start(self, data) -> None:
raw = RawTypingEvent(data)
member_data = data.get("member")
if member_data:
guild = self._get_guild(raw.guild_id)
if guild is not None:
raw.member = Member(data=member_data, guild=guild, state=self)
else:
raw.member = None
else:
raw.member = None
self.dispatch("raw_typing", raw)
channel, guild = self._get_guild_channel(data)
if channel is not None: # pyright: ignore[reportUnnecessaryComparison]
user = raw.member or self._get_typing_user(channel, raw.user_id) # type: ignore
# will be messageable channel if we get here
if user is not None:
self.dispatch("typing", channel, user, raw.when)
def _get_typing_user(
self, channel: Optional[MessageableChannel], user_id: int
) -> Optional[Union[User, Member]]:
if isinstance(channel, DMChannel):
return channel.recipient or self.get_user(user_id)
if isinstance(channel, (Thread, TextChannel)):
return channel.guild.get_member(user_id)
if isinstance(channel, GroupChannel):
return utils.find(lambda x: x.id == user_id, channel.recipients)
return self.get_user(user_id)
def _get_reaction_user(
self, channel: MessageableChannel, user_id: int
) -> Optional[Union[User, Member]]:
if isinstance(channel, TextChannel):
return channel.guild.get_member(user_id)
return self.get_user(user_id)
def get_reaction_emoji(self, data) -> Union[Emoji, PartialEmoji]:
emoji_id = utils.get_as_snowflake(data, "id")
if not emoji_id:
return data["name"]
try:
return self._emojis[emoji_id]
except KeyError:
return PartialEmoji.with_state(
self, animated=data.get("animated", False), id=emoji_id, name=data["name"]
)
def _upgrade_partial_emoji(self, emoji: PartialEmoji) -> Union[Emoji, PartialEmoji, str]:
emoji_id = emoji.id
if not emoji_id:
return emoji.name
try:
return self._emojis[emoji_id]
except KeyError:
return emoji
def get_channel(self, id: Optional[int]) -> Optional[Union[Channel, Thread]]:
if id is None:
return None
pm = self._get_private_channel(id)
if pm is not None:
return pm
for guild in self.guilds:
channel = guild._resolve_channel(id)
if channel is not None:
return channel
return None
def get_scheduled_event(self, id: int) -> Optional[ScheduledEvent]:
for guild in self.guilds:
if event := guild.get_scheduled_event(id):
return event
return None
def create_message(
self,
*,
channel: MessageableChannel,
data: MessagePayload,
) -> Message:
return Message(state=self, channel=channel, data=data)
def create_scheduled_event(
self, *, guild: Guild, data: ScheduledEventPayload
) -> ScheduledEvent:
return ScheduledEvent(state=self, guild=guild, data=data)
def parse_guild_scheduled_event_create(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
event = self.create_scheduled_event(guild=guild, data=data)
guild._add_scheduled_event(event)
self.dispatch("guild_scheduled_event_create", event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_CREATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_update(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["id"])):
old = copy.copy(event)
event._update(data)
self.dispatch("guild_scheduled_event_update", old, event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_UPDATE referencing unknown event ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_UPDATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_delete(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["id"])):
guild._remove_scheduled_event(event.id)
self.dispatch("guild_scheduled_event_delete", event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_DELETE referencing unknown event ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_DELETE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_user_add(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["guild_scheduled_event_id"])):
u = ScheduledEventUser.from_id(
event=event, user_id=int(data["user_id"]), state=self
)
event._add_user(u)
self.dispatch("guild_scheduled_event_user_add", event, u)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_ADD referencing unknown"
" event ID: %s. Discarding.",
data["user_id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_ADD referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_user_remove(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["guild_scheduled_event_id"])):
event._remove_user(int(data["user_id"]))
self.dispatch(
"guild_scheduled_event_user_remove",
event,
ScheduledEventUser.from_id(
event=event, user_id=int(data["user_id"]), state=self
),
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_REMOVE referencing unknown"
" event ID: %s. Discarding.",
data["user_id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_REMOVE referencing unknown"
" guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_auto_moderation_rule_create(self, data) -> None:
self.dispatch(
"auto_moderation_rule_create",
AutoModerationRule(data=data, state=self),
)
def parse_auto_moderation_rule_update(self, data) -> None:
self.dispatch("auto_moderation_rule_update", AutoModerationRule(data=data, state=self))
def parse_auto_moderation_rule_delete(self, data) -> None:
self.dispatch("auto_moderation_rule_delete", AutoModerationRule(data=data, state=self))
def parse_auto_moderation_action_execution(self, data) -> None:
self.dispatch(
"auto_moderation_action_execution", AutoModerationActionExecution(data=data, state=self)
)
def parse_guild_audit_log_entry_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
user_id = None if data.get("user_id") is None else int(data["user_id"])
user = self.get_user(user_id)
users = {} if user_id is None or user is None else {user_id: user}
if guild is not None:
entry = AuditLogEntry(auto_moderation_rules={}, users=users, data=data, guild=guild)
self.dispatch("guild_audit_log_entry_create", entry)
else:
_log.debug(
"guild_audit_log_entry_create wasn't dispatched because the guild (%r) and/or user (%r) are None!",
guild,
user,
)
The provided code snippet includes necessary dependencies for implementing the `get_users_from_interaction` function. Write a Python function `def get_users_from_interaction( state: ConnectionState, interaction: Interaction ) -> List[Union[User, Member]]` to solve the following problem:
Tries to get a list of resolved :class:`User` objects from the interaction data. If possible, it will get resolved :class:`Member` objects instead. Parameters ---------- state: :class:`ConnectionState` State object to construct members with. interaction: :class:`Interaction` Interaction object to attempt to get users/members from. Returns ------- List[Union[:class:`User`, :class:`Member`]] List of resolved users, or members if possible
Here is the function:
def get_users_from_interaction(
state: ConnectionState, interaction: Interaction
) -> List[Union[User, Member]]:
"""Tries to get a list of resolved :class:`User` objects from the interaction data.
If possible, it will get resolved :class:`Member` objects instead.
Parameters
----------
state: :class:`ConnectionState`
State object to construct members with.
interaction: :class:`Interaction`
Interaction object to attempt to get users/members from.
Returns
-------
List[Union[:class:`User`, :class:`Member`]]
List of resolved users, or members if possible
"""
data = interaction.data
ret: List[Union[User, Member]] = []
data = cast(ApplicationCommandInteractionData, data)
# Return a Member object if the required data is available, otherwise fall back to User.
if "resolved" in data and "members" in data["resolved"]:
member_payloads = data["resolved"]["members"]
# Because the payload is modified further down, a copy is made to avoid affecting methods or
# users that read from interaction.data further down the line.
for member_id, member_payload in member_payloads.copy().items():
if interaction.guild is None:
raise TypeError("Cannot resolve members if Interaction.guild is None")
# If a member isn't in the cache, construct a new one.
if (
not (member := interaction.guild.get_member(int(member_id)))
and "users" in data["resolved"]
):
user_payload = data["resolved"]["users"][member_id]
# This is required to construct the Member.
member_payload["user"] = user_payload
member = Member(data=member_payload, guild=interaction.guild, state=state) # type: ignore
interaction.guild._add_member(member)
if member is not None:
ret.append(member)
elif "resolved" in data and "users" in data["resolved"]:
resolved_users_payload = data["resolved"]["users"]
ret = [state.store_user(user_payload) for user_payload in resolved_users_payload.values()]
return ret | Tries to get a list of resolved :class:`User` objects from the interaction data. If possible, it will get resolved :class:`Member` objects instead. Parameters ---------- state: :class:`ConnectionState` State object to construct members with. interaction: :class:`Interaction` Interaction object to attempt to get users/members from. Returns ------- List[Union[:class:`User`, :class:`Member`]] List of resolved users, or members if possible |
160,990 | from __future__ import annotations
import asyncio
import contextlib
import logging
import sys
import warnings
from inspect import Parameter, signature
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Coroutine,
Dict,
Iterable,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
import typing_extensions
from typing_extensions import Annotated
from .abc import GuildChannel
from .channel import (
CategoryChannel,
DMChannel,
ForumChannel,
GroupChannel,
StageChannel,
TextChannel,
VoiceChannel,
)
from .enums import ApplicationCommandOptionType, ApplicationCommandType, ChannelType, Locale
from .errors import (
ApplicationCheckFailure,
ApplicationCommandOptionMissing,
ApplicationError,
ApplicationInvokeError,
)
from .guild import Guild
from .interactions import Interaction
from .member import Member
from .message import Attachment, Message
from .object import Object
from .permissions import Permissions
from .role import Role
from .threads import Thread
from .types.interactions import ApplicationCommandInteractionData
from .user import User
from .utils import MISSING, find, maybe_coroutine, parse_docstring
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class Message(Hashable):
r"""Represents a message from Discord.
.. container:: operations
.. describe:: x == y
Checks if two messages are equal.
.. describe:: x != y
Checks if two messages are not equal.
.. describe:: hash(x)
Returns the message's hash.
Attributes
----------
tts: :class:`bool`
Specifies if the message was done with text-to-speech.
This can only be accurately received in :func:`on_message` due to
a discord limitation.
type: :class:`MessageType`
The type of message. In most cases this should not be checked, but it is helpful
in cases where it might be a system message for :attr:`system_content`.
author: Union[:class:`Member`, :class:`abc.User`]
A :class:`Member` that sent the message. If :attr:`channel` is a
private channel or the user has the left the guild, then it is a :class:`User` instead.
content: :class:`str`
The actual contents of the message.
nonce: Optional[Union[:class:`str`, :class:`int`]]
The value used by the discord guild and the client to verify that the message is successfully sent.
This is not stored long term within Discord's servers and is only used ephemerally.
embeds: List[:class:`Embed`]
A list of embeds the message has.
channel: Union[:class:`TextChannel`, :class:`Thread`, :class:`DMChannel`, :class:`GroupChannel`, :class:`PartialMessageable`]
The :class:`TextChannel` or :class:`Thread` that the message was sent from.
Could be a :class:`DMChannel` or :class:`GroupChannel` if it's a private message.
reference: Optional[:class:`~nextcord.MessageReference`]
The message that this message references. This is only applicable to messages of
type :attr:`MessageType.pins_add`, crossposted messages created by a
followed channel integration, or message replies.
.. versionadded:: 1.5
mention_everyone: :class:`bool`
Specifies if the message mentions everyone.
.. note::
This does not check if the ``@everyone`` or the ``@here`` text is in the message itself.
Rather this boolean indicates if either the ``@everyone`` or the ``@here`` text is in the message
**and** it did end up mentioning.
mentions: List[:class:`abc.User`]
A list of :class:`Member` that were mentioned. If the message is in a private message
then the list will be of :class:`User` instead. For messages that are not of type
:attr:`MessageType.default`\, this array can be used to aid in system messages.
For more information, see :attr:`system_content`.
.. warning::
The order of the mentions list is not in any particular order so you should
not rely on it. This is a Discord limitation, not one with the library.
channel_mentions: List[:class:`abc.GuildChannel`]
A list of :class:`abc.GuildChannel` that were mentioned. If the message is in a private message
then the list is always empty.
role_mentions: List[:class:`Role`]
A list of :class:`Role` that were mentioned. If the message is in a private message
then the list is always empty.
id: :class:`int`
The message ID.
webhook_id: Optional[:class:`int`]
If this message was sent by a webhook, then this is the webhook ID's that sent this
message.
attachments: List[:class:`Attachment`]
A list of attachments given to a message.
pinned: :class:`bool`
Specifies if the message is currently pinned.
flags: :class:`MessageFlags`
Extra features of the message.
.. versionadded:: 1.3
reactions : List[:class:`Reaction`]
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
activity: Optional[:class:`dict`]
The activity associated with this message. Sent with Rich-Presence related messages that for
example, request joining, spectating, or listening to or with another member.
It is a dictionary with the following optional keys:
- ``type``: An integer denoting the type of message activity being requested.
- ``party_id``: The party ID associated with the party.
application: Optional[:class:`dict`]
The rich presence enabled application associated with this message.
It is a dictionary with the following keys:
- ``id``: A string representing the application's ID.
- ``name``: A string representing the application's name.
- ``description``: A string representing the application's description.
- ``icon``: A string representing the icon ID of the application.
- ``cover_image``: A string representing the embed's image asset ID.
stickers: List[:class:`StickerItem`]
A list of sticker items given to the message.
.. versionadded:: 1.6
components: List[:class:`Component`]
A list of components in the message.
.. versionadded:: 2.0
guild: Optional[:class:`Guild`]
The guild that the message belongs to, if applicable.
interaction: Optional[:class:`MessageInteraction`]
The interaction data of a message, if applicable.
"""
__slots__ = (
"_state",
"_edited_timestamp",
"_cs_channel_mentions",
"_cs_raw_mentions",
"_cs_clean_content",
"_cs_raw_channel_mentions",
"_cs_raw_role_mentions",
"_cs_system_content",
"tts",
"content",
"channel",
"webhook_id",
"mention_everyone",
"embeds",
"id",
"interaction",
"mentions",
"author",
"attachments",
"nonce",
"pinned",
"role_mentions",
"type",
"flags",
"reactions",
"reference",
"application",
"activity",
"stickers",
"components",
"_background_tasks",
"guild",
)
if TYPE_CHECKING:
_HANDLERS: ClassVar[List[Tuple[str, Callable[..., None]]]]
_CACHED_SLOTS: ClassVar[List[str]]
guild: Optional[Guild]
reference: Optional[MessageReference]
mentions: List[Union[User, Member]]
author: Union[User, Member]
role_mentions: List[Role]
def __init__(
self,
*,
state: ConnectionState,
channel: MessageableChannel,
data: MessagePayload,
) -> None:
self._state: ConnectionState = state
self.id: int = int(data["id"])
self.webhook_id: Optional[int] = utils.get_as_snowflake(data, "webhook_id")
self.reactions: List[Reaction] = [
Reaction(message=self, data=d) for d in data.get("reactions", [])
]
self.attachments: List[Attachment] = [
Attachment(data=a, state=self._state) for a in data["attachments"]
]
self.embeds: List[Embed] = [Embed.from_dict(a) for a in data["embeds"]]
self.application: Optional[MessageApplicationPayload] = data.get("application")
self.activity: Optional[MessageActivityPayload] = data.get("activity")
self.channel: MessageableChannel = channel
self._edited_timestamp: Optional[datetime.datetime] = utils.parse_time(
data["edited_timestamp"]
)
self.type: MessageType = try_enum(MessageType, data["type"])
self.pinned: bool = data["pinned"]
self.flags: MessageFlags = MessageFlags._from_value(data.get("flags", 0))
self.mention_everyone: bool = data["mention_everyone"]
self.tts: bool = data["tts"]
self.content: str = data["content"]
self.nonce: Optional[Union[int, str]] = data.get("nonce")
self.stickers: List[StickerItem] = [
StickerItem(data=d, state=state) for d in data.get("sticker_items", [])
]
self.components: List[Component] = [
_component_factory(d) for d in data.get("components", [])
]
self._background_tasks: Set[asyncio.Task[None]] = set()
try:
# if the channel doesn't have a guild attribute, we handle that
self.guild = channel.guild # type: ignore
except AttributeError:
if getattr(channel, "type", None) not in (ChannelType.group, ChannelType.private):
self.guild = state._get_guild(utils.get_as_snowflake(data, "guild_id"))
else:
self.guild = None
if (
(thread_data := data.get("thread"))
and not self.thread
and isinstance(self.guild, Guild)
):
self.guild._store_thread(thread_data)
try:
ref = data["message_reference"]
except KeyError:
self.reference = None
else:
self.reference = ref = MessageReference.with_state(state, ref)
try:
resolved = data["referenced_message"]
except KeyError:
pass
else:
if resolved is None:
ref.resolved = DeletedReferencedMessage(ref)
else:
# Right now the channel IDs match but maybe in the future they won't.
if ref.channel_id == channel.id:
chan = channel
else:
chan, _ = state._get_guild_channel(resolved)
# the channel will be the correct type here
ref.resolved = self.__class__(channel=chan, data=resolved, state=state) # type: ignore
for handler in ("author", "member", "mentions", "mention_roles"):
try:
getattr(self, f"_handle_{handler}")(data[handler])
except KeyError:
continue
self.interaction: Optional[MessageInteraction] = (
MessageInteraction(data=data["interaction"], guild=self.guild, state=self._state)
if "interaction" in data
else None
)
def __repr__(self) -> str:
name = self.__class__.__name__
return f"<{name} id={self.id} channel={self.channel!r} type={self.type!r} author={self.author!r} flags={self.flags!r}>"
def _try_patch(self, data, key, transform=None) -> None:
try:
value = data[key]
except KeyError:
pass
else:
if transform is None:
setattr(self, key, value)
else:
setattr(self, key, transform(value))
def _add_reaction(self, data, emoji: Emoji | PartialEmoji | str, user_id) -> Reaction:
finder: Callable[[Reaction], bool] = lambda r: r.emoji == emoji
reaction = utils.find(finder, self.reactions)
is_me = data["me"] = user_id == self._state.self_id
if reaction is None:
reaction = Reaction(message=self, data=data, emoji=emoji)
self.reactions.append(reaction)
else:
reaction.count += 1
if is_me:
reaction.me = is_me
return reaction
def _remove_reaction(
self, data: ReactionPayload, emoji: EmojiInputType, user_id: int
) -> Reaction:
reaction = utils.find(lambda r: r.emoji == emoji, self.reactions)
if reaction is None:
# already removed?
raise ValueError("Emoji already removed?")
# if reaction isn't in the list, we crash. This means discord
# sent bad data, or we stored improperly
reaction.count -= 1
if user_id == self._state.self_id:
reaction.me = False
if reaction.count == 0:
# this raises ValueError if something went wrong as well.
self.reactions.remove(reaction)
return reaction
def _clear_emoji(self, emoji) -> Optional[Reaction]:
to_check = str(emoji)
for index, reaction in enumerate(self.reactions): # noqa: B007
if str(reaction.emoji) == to_check:
break
else:
# didn't find anything so just return
return None
del self.reactions[index]
return reaction
def _update(self, data) -> None:
# In an update scheme, 'author' key has to be handled before 'member'
# otherwise they overwrite each other which is undesirable.
# Since there's no good way to do this we have to iterate over every
# handler rather than iterating over the keys which is a little slower
for key, handler in self._HANDLERS:
try:
value = data[key]
except KeyError:
continue
else:
handler(self, value)
# clear the cached properties
for attr in self._CACHED_SLOTS:
with contextlib.suppress(AttributeError):
delattr(self, attr)
def _handle_edited_timestamp(self, value: str) -> None:
self._edited_timestamp = utils.parse_time(value)
def _handle_pinned(self, value: bool) -> None:
self.pinned = value
def _handle_flags(self, value: int) -> None:
self.flags = MessageFlags._from_value(value)
def _handle_application(self, value: MessageApplicationPayload) -> None:
self.application = value
def _handle_activity(self, value: MessageActivityPayload) -> None:
self.activity = value
def _handle_mention_everyone(self, value: bool) -> None:
self.mention_everyone = value
def _handle_tts(self, value: bool) -> None:
self.tts = value
def _handle_type(self, value: int) -> None:
self.type = try_enum(MessageType, value)
def _handle_content(self, value: str) -> None:
self.content = value
def _handle_attachments(self, value: List[AttachmentPayload]) -> None:
self.attachments = [Attachment(data=a, state=self._state) for a in value]
def _handle_embeds(self, value: List[EmbedPayload]) -> None:
self.embeds = [Embed.from_dict(data) for data in value]
def _handle_nonce(self, value: Union[str, int]) -> None:
self.nonce = value
def _handle_author(self, author: UserPayload) -> None:
self.author = self._state.store_user(author)
if isinstance(self.guild, Guild):
found = self.guild.get_member(self.author.id)
if found is not None:
self.author = found
def _handle_member(self, member: MemberPayload) -> None:
# The gateway now gives us full Member objects sometimes with the following keys
# deaf, mute, joined_at, roles
# For the sake of performance I'm going to assume that the only
# field that needs *updating* would be the joined_at field.
# If there is no Member object (for some strange reason), then we can upgrade
# ourselves to a more "partial" member object.
author = self.author
try:
# Update member reference
author._update_from_message(member) # type: ignore
except AttributeError:
# It's a user here
# TODO: consider adding to cache here
self.author = Member._from_message(message=self, data=member)
def _handle_mentions(self, mentions: List[UserWithMemberPayload]) -> None:
self.mentions = r = []
guild = self.guild
state = self._state
if not isinstance(guild, Guild):
self.mentions = [state.store_user(m) for m in mentions]
return
for mention in filter(None, mentions):
id_search = int(mention["id"])
member = guild.get_member(id_search)
if member is not None:
r.append(member)
else:
r.append(Member._try_upgrade(data=mention, guild=guild, state=state))
def _handle_mention_roles(self, role_mentions: List[int]) -> None:
self.role_mentions = []
if isinstance(self.guild, Guild):
for role_id in map(int, role_mentions):
role = self.guild.get_role(role_id)
if role is not None:
self.role_mentions.append(role)
def _handle_components(self, components: List[ComponentPayload]) -> None:
self.components = [_component_factory(d) for d in components]
def _handle_thread(self, thread: Optional[ThreadPayload]) -> None:
if thread:
self.guild._store_thread(thread) # type: ignore
def _rebind_cached_references(
self, new_guild: Guild, new_channel: Union[TextChannel, Thread]
) -> None:
self.guild = new_guild
self.channel = new_channel
def raw_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of user IDs matched with
the syntax of ``<@user_id>`` in the message content.
This allows you to receive the user IDs of mentioned users
even in a private message context.
"""
return utils.parse_raw_mentions(self.content)
def raw_channel_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of channel IDs matched with
the syntax of ``<#channel_id>`` in the message content.
"""
return utils.parse_raw_channel_mentions(self.content)
def raw_role_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of role IDs matched with
the syntax of ``<@&role_id>`` in the message content.
"""
return utils.parse_raw_role_mentions(self.content)
def channel_mentions(self) -> List[GuildChannel]:
if self.guild is None:
return []
it = filter(None, map(self.guild.get_channel, self.raw_channel_mentions))
return utils.unique(it)
def clean_content(self) -> str:
""":class:`str`: A property that returns the content in a "cleaned up"
manner. This basically means that mentions are transformed
into the way the client shows it. e.g. ``<#id>`` will transform
into ``#name``.
This will also transform @everyone and @here mentions into
non-mentions.
.. note::
This *does not* affect markdown. If you want to escape
or remove markdown then use :func:`utils.escape_markdown` or :func:`utils.remove_markdown`
respectively, along with this function.
"""
transformations = {
re.escape(f"<#{channel.id}>"): "#" + channel.name for channel in self.channel_mentions
}
mention_transforms = {
re.escape(f"<@{member.id}>"): "@" + member.display_name for member in self.mentions
}
# add the <@!user_id> cases as well..
second_mention_transforms = {
re.escape(f"<@!{member.id}>"): "@" + member.display_name for member in self.mentions
}
transformations.update(mention_transforms)
transformations.update(second_mention_transforms)
if self.guild is not None:
role_transforms = {
re.escape(f"<@&{role.id}>"): "@" + role.name for role in self.role_mentions
}
transformations.update(role_transforms)
def repl(obj):
return transformations.get(re.escape(obj.group(0)), "")
pattern = re.compile("|".join(transformations.keys()))
result = pattern.sub(repl, self.content)
return escape_mentions(result)
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: The message's creation time in UTC."""
return utils.snowflake_time(self.id)
def edited_at(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: An aware UTC datetime object containing the edited time of the message."""
return self._edited_timestamp
def jump_url(self) -> str:
""":class:`str`: Returns a URL that allows the client to jump to this message."""
guild_id = getattr(self.guild, "id", "@me")
return f"https://discord.com/channels/{guild_id}/{self.channel.id}/{self.id}"
def thread(self) -> Optional[Thread]:
"""Optional[:class:`Thread`]: The thread started from this message. None if no thread was started."""
if not isinstance(self.guild, Guild):
return None
return self.guild.get_thread(self.id)
def is_system(self) -> bool:
""":class:`bool`: Whether the message is a system message.
A system message is a message that is constructed entirely by the Discord API
in response to something.
.. versionadded:: 1.3
"""
return self.type not in (
MessageType.default,
MessageType.reply,
MessageType.chat_input_command,
MessageType.context_menu_command,
MessageType.thread_starter_message,
)
def system_content(self):
r""":class:`str`: A property that returns the content that is rendered
regardless of the :attr:`Message.type`.
In the case of :attr:`MessageType.default` and :attr:`MessageType.reply`\,
this just returns the regular :attr:`Message.content`. Otherwise this
returns an English message denoting the contents of the system message.
"""
if self.type is MessageType.default:
return self.content
if self.type is MessageType.recipient_add:
if self.channel.type is ChannelType.group:
return f"{self.author.name} added {self.mentions[0].name} to the group."
return f"{self.author.name} added {self.mentions[0].name} to the thread."
if self.type is MessageType.recipient_remove:
if self.channel.type is ChannelType.group:
return f"{self.author.name} removed {self.mentions[0].name} from the group."
return f"{self.author.name} removed {self.mentions[0].name} from the thread."
if self.type is MessageType.channel_name_change:
return f"{self.author.name} changed the channel name: **{self.content}**"
if self.type is MessageType.channel_icon_change:
return f"{self.author.name} changed the channel icon."
if self.type is MessageType.pins_add:
return f"{self.author.name} pinned a message to this channel."
if self.type is MessageType.new_member:
formats = [
"{0} joined the party.",
"{0} is here.",
"Welcome, {0}. We hope you brought pizza.",
"A wild {0} appeared.",
"{0} just landed.",
"{0} just slid into the server.",
"{0} just showed up!",
"Welcome {0}. Say hi!",
"{0} hopped into the server.",
"Everyone welcome {0}!",
"Glad you're here, {0}.",
"Good to see you, {0}.",
"Yay you made it, {0}!",
]
created_at_ms = int(self.created_at.timestamp() * 1000)
return formats[created_at_ms % len(formats)].format(self.author.name)
if self.type is MessageType.premium_guild_subscription:
if not self.content:
return f"{self.author.name} just boosted the server!"
return f"{self.author.name} just boosted the server **{self.content}** times!"
if self.type is MessageType.premium_guild_tier_1:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 1!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 1!**"
if self.type is MessageType.premium_guild_tier_2:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 2!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 2!**"
if self.type is MessageType.premium_guild_tier_3:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 3!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 3!**"
if self.type is MessageType.channel_follow_add:
return f"{self.author.name} has added {self.content} to this channel"
if self.type is MessageType.guild_stream:
# the author will be a Member
return f"{self.author.name} is live! Now streaming {self.author.activity.name}" # type: ignore
if self.type is MessageType.guild_discovery_disqualified:
return "This server has been removed from Server Discovery because it no longer passes all the requirements. Check Server Settings for more details."
if self.type is MessageType.guild_discovery_requalified:
return "This server is eligible for Server Discovery again and has been automatically relisted!"
if self.type is MessageType.guild_discovery_grace_period_initial_warning:
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."
if self.type is MessageType.guild_discovery_grace_period_final_warning:
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."
if self.type is MessageType.thread_created:
return f"{self.author.name} started a thread: **{self.content}**. See all **threads**."
if self.type is MessageType.reply:
return self.content
if self.type is MessageType.thread_starter_message:
if self.reference is None or self.reference.resolved is None:
return "Sorry, we couldn't load the first message in this thread"
# the resolved message for the reference will be a Message
return self.reference.resolved.content # type: ignore
if self.type is MessageType.guild_invite_reminder:
return "Wondering who to invite?\nStart by inviting anyone who can help you build the server!"
if self.type is MessageType.stage_start:
return f"{self.author.display_name} started {self.content}"
if self.type is MessageType.stage_end:
return f"{self.author.display_name} ended {self.content}"
if self.type is MessageType.stage_speaker:
return f"{self.author.display_name} is now a speaker."
if self.type is MessageType.stage_topic:
return f"{self.author.display_name} changed the Stage topic: {self.content}"
return None
async def delete(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the message.
Your own messages could be deleted without any proper permissions. However to
delete other people's messages, you need the :attr:`~Permissions.manage_messages`
permission.
.. versionchanged:: 1.1
Added the new ``delay`` keyword-only parameter.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message. If the deletion fails then it is silently ignored.
Raises
------
Forbidden
You do not have proper permissions to delete the message.
NotFound
The message was deleted already
HTTPException
Deleting the message failed.
"""
if delay is not None:
async def delete(delay: float) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await self._state.http.delete_message(self.channel.id, self.id)
task = asyncio.create_task(delete(delay))
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await self._state.http.delete_message(self.channel.id, self.id)
async def edit(
self,
*,
content: Optional[str] = ...,
embed: Optional[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
file: Optional[File] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embeds: List[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
file: Optional[File] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embed: Optional[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
files: Optional[List[File]] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embeds: List[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
files: Optional[List[File]] = ...,
) -> Message:
...
async def edit(
self,
content: Optional[str] = MISSING,
embed: Optional[Embed] = MISSING,
embeds: List[Embed] = MISSING,
attachments: List[Attachment] = MISSING,
suppress: bool = MISSING,
delete_after: Optional[float] = None,
allowed_mentions: Optional[AllowedMentions] = MISSING,
view: Optional[View] = MISSING,
file: Optional[File] = MISSING,
files: Optional[List[File]] = MISSING,
) -> Message:
"""|coro|
Edits the message.
The content must be able to be transformed into a string via ``str(content)``.
.. versionchanged:: 1.3
The ``suppress`` keyword-only parameter was added.
Parameters
----------
content: Optional[:class:`str`]
The new content to replace the message with.
Could be ``None`` to remove the content.
embed: Optional[:class:`Embed`]
The new embed to replace the original with.
Could be ``None`` to remove the embed.
embeds: List[:class:`Embed`]
The new embeds to replace the original with. Must be a maximum of 10.
To remove all embeds ``[]`` should be passed.
.. versionadded:: 2.0
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep all existing attachments,
pass ``message.attachments``.
suppress: :class:`bool`
Whether to suppress embeds for the message. This removes
all the embeds if set to ``True``. If set to ``False``
this brings the embeds back if they were suppressed.
Using this parameter requires :attr:`~.Permissions.manage_messages`.
delete_after: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message we just edited. If the deletion fails,
then it is silently ignored.
allowed_mentions: Optional[:class:`~nextcord.AllowedMentions`]
Controls the mentions being processed in this message. If this is
passed, then the object is merged with :attr:`~nextcord.Client.allowed_mentions`.
The merging behaviour only overrides attributes that have been explicitly passed
to the object, otherwise it uses the attributes set in :attr:`~nextcord.Client.allowed_mentions`.
If no object is passed at all then the defaults given by :attr:`~nextcord.Client.allowed_mentions`
are used instead.
.. versionadded:: 1.4
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
file: Optional[:class:`File`]
If provided, a new file to add to the message.
.. versionadded:: 2.0
files: Optional[List[:class:`File`]]
If provided, a list of new files to add to the message.
.. versionadded:: 2.0
Raises
------
HTTPException
Editing the message failed.
Forbidden
Tried to suppress a message without permissions or
edited a message's content or embed that isn't yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
Returns
-------
:class:`Message`
The edited message.
"""
payload: Dict[str, Any] = {}
if content is not MISSING:
if content is not None:
payload["content"] = str(content)
else:
payload["content"] = None
if embed is not MISSING and embeds is not MISSING:
raise InvalidArgument("Cannot pass both embed and embeds parameter to edit()")
if file is not MISSING and files is not MISSING:
raise InvalidArgument("Cannot pass both file and files parameter to edit()")
if embed is not MISSING:
if embed is None:
payload["embeds"] = []
else:
payload["embeds"] = [embed.to_dict()]
elif embeds is not MISSING:
payload["embeds"] = [e.to_dict() for e in embeds]
if suppress is not MISSING:
flags = MessageFlags._from_value(self.flags.value)
flags.suppress_embeds = suppress
payload["flags"] = flags.value
if allowed_mentions is MISSING:
if self._state.allowed_mentions is not None and self.author.id == self._state.self_id:
payload["allowed_mentions"] = self._state.allowed_mentions.to_dict()
elif allowed_mentions is not None:
if self._state.allowed_mentions is not None:
payload["allowed_mentions"] = self._state.allowed_mentions.merge(
allowed_mentions
).to_dict()
else:
payload["allowed_mentions"] = allowed_mentions.to_dict()
if attachments is not MISSING:
payload["attachments"] = [a.to_dict() for a in attachments]
if view is not MISSING:
self._state.prevent_view_updates_for(self.id)
if view:
payload["components"] = view.to_components()
else:
payload["components"] = []
if file is not MISSING:
payload["files"] = [file]
elif files is not MISSING:
payload["files"] = files
data = await self._state.http.edit_message(self.channel.id, self.id, **payload)
message = Message(state=self._state, channel=self.channel, data=data)
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, self.id)
if delete_after is not None:
await self.delete(delay=delete_after)
return message
async def publish(self) -> None:
"""|coro|
Publishes this message to your announcement channel.
You must have the :attr:`~Permissions.send_messages` permission to do this.
If the message is not your own then the :attr:`~Permissions.manage_messages`
permission is also needed.
Raises
------
Forbidden
You do not have the proper permissions to publish this message.
HTTPException
Publishing the message failed.
"""
await self._state.http.publish_message(self.channel.id, self.id)
async def pin(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Pins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Parameters
----------
reason: Optional[:class:`str`]
The reason for pinning the message. Shows up on the audit log.
.. versionadded:: 1.4
Raises
------
Forbidden
You do not have permissions to pin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Pinning the message failed, probably due to the channel
having more than 50 pinned messages.
"""
await self._state.http.pin_message(self.channel.id, self.id, reason=reason)
self.pinned = True
async def unpin(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Unpins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Parameters
----------
reason: Optional[:class:`str`]
The reason for unpinning the message. Shows up on the audit log.
.. versionadded:: 1.4
Raises
------
Forbidden
You do not have permissions to unpin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Unpinning the message failed.
"""
await self._state.http.unpin_message(self.channel.id, self.id, reason=reason)
self.pinned = False
async def add_reaction(self, emoji: EmojiInputType) -> None:
"""|coro|
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You must have the :attr:`~Permissions.read_message_history` permission
to use this. If nobody else has reacted to the message using this
emoji, the :attr:`~Permissions.add_reactions` permission is required.
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to react with.
Raises
------
HTTPException
Adding the reaction failed.
Forbidden
You do not have the proper permissions to react to the message.
NotFound
The emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
await self._state.http.add_reaction(self.channel.id, self.id, emoji)
async def remove_reaction(
self, emoji: Union[EmojiInputType, Reaction], member: Snowflake
) -> None:
"""|coro|
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
If the reaction is not your own (i.e. ``member`` parameter is not you) then
the :attr:`~Permissions.manage_messages` permission is needed.
The ``member`` parameter must represent a member and meet
the :class:`abc.Snowflake` abc.
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to remove.
member: :class:`abc.Snowflake`
The member for which to remove the reaction.
Raises
------
HTTPException
Removing the reaction failed.
Forbidden
You do not have the proper permissions to remove the reaction.
NotFound
The member or emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
if member.id == self._state.self_id:
await self._state.http.remove_own_reaction(self.channel.id, self.id, emoji)
else:
await self._state.http.remove_reaction(self.channel.id, self.id, emoji, member.id)
async def clear_reaction(self, emoji: Union[EmojiInputType, Reaction]) -> None:
"""|coro|
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You need the :attr:`~Permissions.manage_messages` permission to use this.
.. versionadded:: 1.3
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to clear.
Raises
------
HTTPException
Clearing the reaction failed.
Forbidden
You do not have the proper permissions to clear the reaction.
NotFound
The emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
await self._state.http.clear_single_reaction(self.channel.id, self.id, emoji)
async def clear_reactions(self) -> None:
"""|coro|
Removes all the reactions from the message.
You need the :attr:`~Permissions.manage_messages` permission to use this.
Raises
------
HTTPException
Removing the reactions failed.
Forbidden
You do not have the proper permissions to remove all the reactions.
"""
await self._state.http.clear_reactions(self.channel.id, self.id)
async def create_thread(
self, *, name: str, auto_archive_duration: ThreadArchiveDuration = MISSING
) -> Thread:
"""|coro|
Creates a public thread from this message.
You must have :attr:`~nextcord.Permissions.create_public_threads` in order to
create a public thread from a message.
The channel this message belongs in must be a :class:`TextChannel`.
.. versionadded:: 2.0
Parameters
----------
name: :class:`str`
The name of the thread.
auto_archive_duration: :class:`int`
The duration in minutes before a thread is automatically archived for inactivity.
If not provided, the channel's default auto archive duration is used.
Raises
------
Forbidden
You do not have permissions to create a thread.
HTTPException
Creating the thread failed.
InvalidArgument
This message does not have guild info attached.
Returns
-------
:class:`.Thread`
The created thread.
"""
if self.guild is None:
raise InvalidArgument("This message does not have guild info attached.")
default_auto_archive_duration: ThreadArchiveDuration = getattr(
self.channel, "default_auto_archive_duration", 1440
)
data = await self._state.http.start_thread_with_message(
self.channel.id,
self.id,
name=name,
auto_archive_duration=auto_archive_duration or default_auto_archive_duration,
)
return Thread(guild=self.guild, state=self._state, data=data)
async def reply(self, content: Optional[str] = None, **kwargs) -> Message:
"""|coro|
A shortcut method to :meth:`.abc.Messageable.send` to reply to the
:class:`.Message`.
.. versionadded:: 1.6
Raises
------
~nextcord.HTTPException
Sending the message failed.
~nextcord.Forbidden
You do not have the proper permissions to send the message.
~nextcord.InvalidArgument
The ``files`` list is not of the appropriate size or
you specified both ``file`` and ``files``.
Returns
-------
:class:`.Message`
The message that was sent.
"""
return await self.channel.send(content, reference=self, **kwargs)
def to_reference(self, *, fail_if_not_exists: bool = True) -> MessageReference:
"""Creates a :class:`~nextcord.MessageReference` from the current message.
.. versionadded:: 1.6
Parameters
----------
fail_if_not_exists: :class:`bool`
Whether replying using the message reference should raise :class:`HTTPException`
if the message no longer exists or Discord could not fetch the message.
.. versionadded:: 1.7
Returns
-------
:class:`~nextcord.MessageReference`
The reference to this message.
"""
return MessageReference.from_message(self, fail_if_not_exists=fail_if_not_exists)
def to_message_reference_dict(self) -> MessageReferencePayload:
data: MessageReferencePayload = {
"message_id": self.id,
"channel_id": self.channel.id,
}
if self.guild is not None:
data["guild_id"] = self.guild.id
return data
class ApplicationCommandInteractionData(TypedDict):
id: Snowflake
name: str
type: ApplicationCommandType
options: NotRequired[List[ApplicationCommandInteractionDataOption]]
resolved: NotRequired[ApplicationCommandInteractionDataResolved]
target_id: NotRequired[Snowflake]
class ConnectionState:
if TYPE_CHECKING:
_get_websocket: Callable[..., DiscordWebSocket]
_get_client: Callable[..., Client]
_parsers: Dict[str, Callable[[Dict[str, Any]], None]]
def __init__(
self,
*,
dispatch: Callable,
handlers: Dict[str, Callable],
hooks: Dict[str, Callable],
http: HTTPClient,
loop: asyncio.AbstractEventLoop,
max_messages: Optional[int] = 1000,
application_id: Optional[int] = None,
heartbeat_timeout: float = 60.0,
guild_ready_timeout: float = 2.0,
allowed_mentions: Optional[AllowedMentions] = None,
activity: Optional[BaseActivity] = None,
status: Optional[Status] = None,
intents: Intents = Intents.default(),
chunk_guilds_at_startup: bool = MISSING,
member_cache_flags: MemberCacheFlags = MISSING,
) -> None:
self.loop: asyncio.AbstractEventLoop = loop
self.http: HTTPClient = http
self.max_messages: Optional[int] = max_messages
if self.max_messages is not None and self.max_messages <= 0:
self.max_messages = 1000
self.dispatch: Callable = dispatch
self.handlers: Dict[str, Callable] = handlers
self.hooks: Dict[str, Callable] = hooks
self.shard_count: Optional[int] = None
self._ready_task: Optional[asyncio.Task] = None
self.application_id: Optional[int] = application_id
self.heartbeat_timeout: float = heartbeat_timeout
self.guild_ready_timeout: float = guild_ready_timeout
if self.guild_ready_timeout < 0:
raise ValueError("guild_ready_timeout cannot be negative")
if allowed_mentions is not None and not isinstance(allowed_mentions, AllowedMentions):
raise TypeError("allowed_mentions parameter must be AllowedMentions")
self.allowed_mentions: Optional[AllowedMentions] = allowed_mentions
self._chunk_requests: Dict[Union[int, str], ChunkRequest] = {}
self._chunk_tasks: Dict[Union[int, str], asyncio.Task[None]] = {}
self._background_tasks: Set[asyncio.Task] = set()
if activity is not None:
if not isinstance(activity, BaseActivity):
raise TypeError("activity parameter must derive from BaseActivity.")
raw_activity = activity.to_dict()
else:
raw_activity = activity
raw_status = ("invisible" if status is Status.offline else str(status)) if status else None
if not isinstance(intents, Intents):
raise TypeError(f"intents parameter must be Intent not {type(intents)!r}")
if not intents.guilds:
_log.warning("Guilds intent seems to be disabled. This may cause state related issues.")
if chunk_guilds_at_startup is MISSING:
chunk_guilds_at_startup = intents.members
self._chunk_guilds: bool = chunk_guilds_at_startup
# Ensure these two are set properly
if not intents.members and self._chunk_guilds:
raise ValueError("Intents.members must be enabled to chunk guilds at startup.")
if member_cache_flags is MISSING:
member_cache_flags = MemberCacheFlags.from_intents(intents)
else:
if not isinstance(member_cache_flags, MemberCacheFlags):
raise TypeError(
"member_cache_flags parameter must be MemberCacheFlags "
f"not {type(member_cache_flags)!r}"
)
member_cache_flags._verify_intents(intents)
self.member_cache_flags: MemberCacheFlags = member_cache_flags
self._activity: Optional[ActivityPayload] = raw_activity
self._status: Optional[str] = raw_status
self._intents: Intents = intents
# A set of all application command objects available. Set because duplicates should not exist.
self._application_commands: Set[BaseApplicationCommand] = set()
# A dictionary of all available unique command signatures. Compiled at runtime because needing to iterate
# through all application commands would take far more time. If memory is problematic, perhaps this can go?
self._application_command_signatures: Dict[
Tuple[Optional[str], int, Optional[int]], BaseApplicationCommand
] = {}
# A dictionary of Discord Application Command ID's and the ApplicationCommand object they correspond to.
self._application_command_ids: Dict[int, BaseApplicationCommand] = {}
if not intents.members or member_cache_flags._empty:
self.store_user = self.create_user
self.deref_user = self.deref_user_no_intents
self.parsers = parsers = {}
for attr, func in inspect.getmembers(self):
if attr.startswith("parse_"):
parsers[attr[6:].upper()] = func
self.clear()
def clear(self, *, views: bool = True, modals: bool = True) -> None:
self.user: Optional[ClientUser] = None
# Originally, this code used WeakValueDictionary to maintain references to the
# global user mapping.
# However, profiling showed that this came with two cons:
# 1. The __weakref__ slot caused a non-trivial increase in memory
# 2. The performance of the mapping caused store_user to be a bottleneck.
# Since this is undesirable, a mapping is now used instead with stored
# references now using a regular dictionary with eviction being done
# using __del__. Testing this for memory leaks led to no discernible leaks,
# though more testing will have to be done.
self._users: Dict[int, User] = {}
self._emojis: Dict[int, Emoji] = {}
self._stickers: Dict[int, GuildSticker] = {}
self._guilds: Dict[int, Guild] = {}
# TODO: Why aren't the above and stuff below application_commands declared in __init__?
self._application_commands = set()
# Thought about making these two weakref.WeakValueDictionary's, but the bot could theoretically be holding on
# to them in a dev-defined, which would desync the bot from itself.
self._application_command_signatures = {}
self._application_command_ids = {}
if views:
self._view_store: ViewStore = ViewStore(self)
if modals:
self._modal_store: ModalStore = ModalStore(self)
self._voice_clients: Dict[int, VoiceProtocol] = {}
# LRU of max size 128
self._private_channels: OrderedDict[int, PrivateChannel] = OrderedDict()
# extra dict to look up private channels by user id
self._private_channels_by_user: Dict[int, DMChannel] = {}
if self.max_messages is not None:
self._messages: Optional[Deque[Message]] = deque(maxlen=self.max_messages)
else:
self._messages: Optional[Deque[Message]] = None
def process_chunk_requests(
self, guild_id: int, nonce: Optional[str], members: List[Member], complete: bool
) -> None:
removed = []
for key, request in self._chunk_requests.items():
if request.guild_id == guild_id and request.nonce == nonce:
request.add_members(members)
if complete:
request.done()
removed.append(key)
for key in removed:
del self._chunk_requests[key]
def call_handlers(self, key: str, *args: Any, **kwargs: Any) -> None:
try:
func = self.handlers[key]
except KeyError:
pass
else:
func(*args, **kwargs)
async def call_hooks(self, key: str, *args: Any, **kwargs: Any) -> None:
try:
coro = self.hooks[key]
except KeyError:
pass
else:
await coro(*args, **kwargs)
def self_id(self) -> Optional[int]:
u = self.user
return u.id if u else None
def intents(self) -> Intents:
ret = Intents.none()
ret.value = self._intents.value
return ret
def voice_clients(self) -> List[VoiceProtocol]:
return list(self._voice_clients.values())
def _get_voice_client(self, guild_id: Optional[int]) -> Optional[VoiceProtocol]:
# the keys of self._voice_clients are ints
return self._voice_clients.get(guild_id) # type: ignore
def _add_voice_client(self, guild_id: int, voice: VoiceProtocol) -> None:
self._voice_clients[guild_id] = voice
def _remove_voice_client(self, guild_id: int) -> None:
self._voice_clients.pop(guild_id, None)
def _update_references(self, ws: DiscordWebSocket) -> None:
for vc in self.voice_clients:
vc.main_ws = ws # type: ignore
def store_user(self, data: UserPayload) -> User:
user_id = int(data["id"])
try:
return self._users[user_id]
except KeyError:
user = User(state=self, data=data)
if user.discriminator != "0000":
self._users[user_id] = user
user._stored = True
return user
def deref_user(self, user_id: int) -> None:
self._users.pop(user_id, None)
def create_user(self, data: Union[PartialUserPayload, UserPayload]) -> User:
return User(state=self, data=data)
def deref_user_no_intents(self, user_id: int) -> None:
return
def get_user(self, id: Optional[int]) -> Optional[User]:
# the keys of self._users are ints
return self._users.get(id) # type: ignore
def store_emoji(self, guild: Guild, data: EmojiPayload) -> Emoji:
# the id will be present here
emoji_id = int(data["id"]) # type: ignore
self._emojis[emoji_id] = emoji = Emoji(guild=guild, state=self, data=data)
return emoji
def store_sticker(self, guild: Guild, data: GuildStickerPayload) -> GuildSticker:
sticker_id = int(data["id"])
self._stickers[sticker_id] = sticker = GuildSticker(state=self, data=data)
return sticker
def store_view(self, view: View, message_id: Optional[int] = None) -> None:
self._view_store.add_view(view, message_id)
def store_modal(self, modal: Modal, user_id: Optional[int] = None) -> None:
self._modal_store.add_modal(modal, user_id)
def remove_view(self, view: View, message_id: Optional[int] = None) -> None:
self._view_store.remove_view(view, message_id)
def remove_modal(self, modal: Modal) -> None:
self._modal_store.remove_modal(modal)
def prevent_view_updates_for(self, message_id: Optional[int]) -> Optional[View]:
return self._view_store.remove_message_tracking(message_id) # type: ignore
def all_views(self) -> List[View]:
return self._view_store.all_views()
def views(self, persistent: bool = True) -> List[View]:
return self._view_store.views(persistent)
def guilds(self) -> List[Guild]:
return list(self._guilds.values())
def _get_guild(self, guild_id: Optional[int]) -> Optional[Guild]:
# the keys of self._guilds are ints
return self._guilds.get(guild_id) # type: ignore
def _add_guild(self, guild: Guild) -> None:
self._guilds[guild.id] = guild
def _remove_guild(self, guild: Guild) -> None:
self._guilds.pop(guild.id, None)
for emoji in guild.emojis:
self._emojis.pop(emoji.id, None)
for sticker in guild.stickers:
self._stickers.pop(sticker.id, None)
del guild
def emojis(self) -> List[Emoji]:
return list(self._emojis.values())
def stickers(self) -> List[GuildSticker]:
return list(self._stickers.values())
def get_emoji(self, emoji_id: Optional[int]) -> Optional[Emoji]:
# the keys of self._emojis are ints
return self._emojis.get(emoji_id) # type: ignore
def get_sticker(self, sticker_id: Optional[int]) -> Optional[GuildSticker]:
# the keys of self._stickers are ints
return self._stickers.get(sticker_id) # type: ignore
def private_channels(self) -> List[PrivateChannel]:
return list(self._private_channels.values())
def _get_private_channel(self, channel_id: Optional[int]) -> Optional[PrivateChannel]:
try:
# the keys of self._private_channels are ints
value = self._private_channels[channel_id] # type: ignore
except KeyError:
return None
else:
self._private_channels.move_to_end(channel_id) # type: ignore
return value
def _get_private_channel_by_user(self, user_id: Optional[int]) -> Optional[DMChannel]:
# the keys of self._private_channels are ints
return self._private_channels_by_user.get(user_id) # type: ignore
def _add_private_channel(self, channel: PrivateChannel) -> None:
channel_id = channel.id
self._private_channels[channel_id] = channel
if len(self._private_channels) > 128:
_, to_remove = self._private_channels.popitem(last=False)
if isinstance(to_remove, DMChannel) and to_remove.recipient:
self._private_channels_by_user.pop(to_remove.recipient.id, None)
if isinstance(channel, DMChannel) and channel.recipient:
self._private_channels_by_user[channel.recipient.id] = channel
def add_dm_channel(self, data: DMChannelPayload) -> DMChannel:
# self.user is *always* cached when this is called
channel = DMChannel(me=self.user, state=self, data=data) # type: ignore
self._add_private_channel(channel)
return channel
def _remove_private_channel(self, channel: PrivateChannel) -> None:
self._private_channels.pop(channel.id, None)
if isinstance(channel, DMChannel):
recipient = channel.recipient
if recipient is not None:
self._private_channels_by_user.pop(recipient.id, None)
def _get_message(self, msg_id: Optional[int]) -> Optional[Message]:
return (
utils.find(lambda m: m.id == msg_id, reversed(self._messages))
if self._messages
else None
)
def _add_guild_from_data(self, data: GuildPayload) -> Guild:
guild = Guild(data=data, state=self)
self._add_guild(guild)
return guild
def _guild_needs_chunking(self, guild: Guild) -> bool:
# If presences are enabled then we get back the old guild.large behaviour
return (
self._chunk_guilds
and not guild.chunked
and not (self._intents.presences and not guild.large)
)
def _get_guild_channel(
self, data: MessagePayload
) -> Tuple[Union[Channel, Thread], Optional[Guild]]:
channel_id = int(data["channel_id"])
try:
guild = self._get_guild(int(data["guild_id"]))
except KeyError:
channel = self.get_channel(channel_id)
if channel is None:
channel = DMChannel._from_message(self, channel_id)
guild = getattr(channel, "guild", None)
else:
channel = guild and guild._resolve_channel(channel_id)
return channel or PartialMessageable(state=self, id=channel_id), guild
def application_commands(self) -> Set[BaseApplicationCommand]:
"""Gets a copy of the ApplicationCommand object set. If the original is given out and modified, massive desyncs
may occur. This should be used internally as well if size-changed-during-iteration is a worry.
"""
return self._application_commands.copy()
def get_application_command(self, command_id: int) -> Optional[BaseApplicationCommand]:
return self._application_command_ids.get(command_id, None)
def get_application_command_from_signature(
self,
*,
type: int,
qualified_name: str,
guild_id: Optional[int],
search_localizations: bool = False,
) -> Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]]:
def get_parent_command(name: str, /) -> Optional[BaseApplicationCommand]:
found = self._application_command_signatures.get((name, type, guild_id))
if not search_localizations:
return found
for command in self._application_command_signatures.values():
if command.name_localizations and name in command.name_localizations.values():
found = command
break
return found
def find_children(
parent: Union[BaseApplicationCommand, SlashApplicationSubcommand], name: str, /
) -> Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]]:
children: Dict[str, SlashApplicationSubcommand] = getattr(parent, "children", {})
if not children:
return parent
found = children.get(name)
if not search_localizations:
return found
subcommand: Union[BaseApplicationCommand, SlashApplicationSubcommand]
for subcommand in children.values():
if subcommand.name_localizations and name in subcommand.name_localizations.values():
found = subcommand
break
return found
parent: Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]] = None
if not qualified_name:
return None
if " " not in qualified_name:
return get_parent_command(qualified_name)
for command_name in qualified_name.split(" "):
if parent is None:
parent = get_parent_command(command_name)
else:
parent = find_children(parent, command_name)
return parent
def get_guild_application_commands(
self, guild_id: Optional[int] = None, rollout: bool = False
) -> List[BaseApplicationCommand]:
"""Gets all commands that have the given guild ID. If guild_id is None, all guild commands are returned. if
rollout is True, guild_ids_to_rollout is used.
"""
return [
app_cmd
for app_cmd in self.application_commands
if guild_id is None
or guild_id in app_cmd.guild_ids
or (rollout and guild_id in app_cmd.guild_ids_to_rollout)
]
def get_global_application_commands(
self, rollout: bool = False
) -> List[BaseApplicationCommand]:
"""Gets all commands that are registered globally. If rollout is True, is_global is used."""
return [
app_cmd
for app_cmd in self.application_commands
if (rollout and app_cmd.is_global) or None in app_cmd.command_ids
]
def add_application_command(
self,
command: BaseApplicationCommand,
*,
overwrite: bool = False,
use_rollout: bool = False,
pre_remove: bool = True,
) -> None:
"""Adds the command to the state and updates the state with any changes made to the command.
Removes all existing references, then adds them.
Safe to call multiple times on the same application command.
Parameters
----------
command: :class:`BaseApplicationCommand`
The command to add/update the state with.
overwrite: :class:`bool`
If the library will let you add a command that overlaps with an existing command. Default ``False``.
use_rollout: :class:`bool`
If the command should be added to the state with its rollout guild IDs.
pre_remove: :class:`bool`
If the command should be removed before adding it. This will clear all signatures from storage, including
rollout ones.
"""
if pre_remove:
self.remove_application_command(command)
signature_set = (
command.get_rollout_signatures() if use_rollout else command.get_signatures()
)
for signature in signature_set:
if not overwrite and (
found_command := self._application_command_signatures.get(signature, None)
):
if found_command is not command:
raise ValueError(
f"{command.error_name} You cannot add application commands with duplicate "
f"signatures."
)
# No else because we do not care if the command has its own signature already in.
else:
self._application_command_signatures[signature] = command
for command_id in command.command_ids.values():
# PyCharm flags found_command as it "might be referenced before assignment", but that can't happen due to it
# being in an AND statement.
# noinspection PyUnboundLocalVariable
if (
not overwrite
and (found_command := self._application_command_ids.get(command_id, None))
and found_command is not command
):
raise ValueError(
f"{command.error_name} You cannot add application commands with duplicate IDs."
)
self._application_command_ids[command_id] = command
# TODO: Add the command to guilds. Should it? Check if it does in the Guild add.
self._application_commands.add(command)
def remove_application_command(self, command: BaseApplicationCommand) -> None:
"""Removes the command and all signatures + associated IDs from the state.
Safe to call with commands that aren't in the state.
Parameters
----------
command: :class:`BaseApplicationCommand`
the command to remove from the state.
"""
signature_set = command.get_rollout_signatures()
for signature in signature_set:
self._application_command_signatures.pop(signature, None)
for cmd_id in command.command_ids.values():
self._application_command_ids.pop(cmd_id, None)
self._application_commands.discard(command)
def add_all_rollout_signatures(self) -> None:
"""This adds all command signatures for rollouts to the signature cache."""
for command in self._application_commands:
self.add_application_command(command, use_rollout=True)
async def sync_all_application_commands(
self,
data: Optional[Dict[Optional[int], List[ApplicationCommandPayload]]] = None,
*,
use_rollout: bool = True,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
ignore_forbidden: bool = True,
):
"""|coro|
Syncs all application commands with Discord. Will sync global commands if any commands added are global, and
syncs with all guilds that have an application command targeting them.
This may call Discord many times depending on how different guilds you have local commands for, and how many
commands Discord needs to be updated or added, which may cause your bot to be rate limited or even Cloudflare
banned in VERY extreme cases.
This may incur high CPU usage depending on how many commands you have and how complex they are, which may cause
your bot to halt while it checks local commands against the existing commands that Discord has.
For a more targeted version of this method, see :func:`Client.sync_application_commands`
Parameters
----------
data: Optional[Dict[Optional[:class:`int`], List[:class:`dict`]]]
Data to use when comparing local application commands to what Discord has. The key should be the
:class:`int` guild ID (`None` for global) corresponding to the value list of application command payloads
from Discord. Any guild ID's not provided will be fetched if needed. Defaults to ``None``
use_rollout: :class:`bool`
If the rollout guild IDs of commands should be used. Defaults to ``True``
associate_known: :class:`bool`
If local commands that match a command already on Discord should be associated with each other.
Defaults to ``True``
delete_unknown: :class:`bool`
If commands on Discord that don't match a local command should be deleted. Defaults to ``True``.
update_known: :class:`bool`
If commands on Discord have a basic match with a local command, but don't fully match, should be updated.
Defaults to ``True``
register_new: :class:`bool`
If a local command that doesn't have a basic match on Discord should be added to Discord.
Defaults to ``True``
ignore_forbidden: :class:`bool`
If this command should raise an :class:`errors.Forbidden` exception when the bot encounters a guild where
it doesn't have permissions to view application commands.
Defaults to ``True``
"""
_log.debug("Beginning sync of all application commands.")
self._get_client().add_all_application_commands()
data = {} if data is None else data.copy()
if self.application_id is None:
raise TypeError("Could not get the current application's id")
for app_cmd in self.application_commands:
self.add_application_command(command=app_cmd, use_rollout=use_rollout)
if app_cmd.is_global and None not in data:
data[None] = await self.http.get_global_commands(self.application_id)
_log.debug("Fetched global application command data.")
if app_cmd.is_guild:
for guild_id in app_cmd.guild_ids_to_rollout if use_rollout else app_cmd.guild_ids:
if guild_id not in data:
try:
data[guild_id] = await self.http.get_guild_commands(
self.application_id, guild_id
)
_log.debug(
"Fetched guild application command data for guild ID %s", guild_id
)
except Forbidden as e:
if ignore_forbidden:
_log.warning(
"nextcord.Client: Forbidden error for %s, is the applications.commands "
"Oauth scope enabled? %s",
guild_id,
e,
)
else:
raise e
for guild_id in data:
_log.debug("Running sync for %s", "global" if guild_id is None else f"Guild {guild_id}")
await self.sync_application_commands(
data=data[guild_id],
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
register_new=register_new,
)
async def sync_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
) -> None:
"""|coro|
Syncs the locally added application commands with the Guild corresponding to the given ID, or syncs
global commands if the guild_id is ``None``.
Parameters
----------
data: Optional[List[:class:`dict`]]
Data to use when comparing local application commands to what Discord has. Should be a list of application
command data from Discord. If left as ``None``, it will be fetched if needed. Defaults to ``None``.
guild_id: Optional[:class:`int`]
ID of the guild to sync application commands with. If set to ``None``, global commands will be synced instead.
Defaults to ``None``.
associate_known: :class:`bool`
If local commands that match a command already on Discord should be associated with each other.
Defaults to ``True``.
delete_unknown: :class:`bool`
If commands on Discord that don't match a local command should be deleted. Defaults to ``True``.
update_known: :class:`bool`
If commands on Discord have a basic match with a local command, but don't fully match, should be updated.
Defaults to ``True``.
register_new: :class:`bool`
If a local command that doesn't have a basic match on Discord should be added to Discord.
Defaults to ``True``.
"""
_log.debug("Syncing commands to %s", guild_id)
if self.application_id is None:
raise TypeError("Could not get the current application's id")
if not data:
if guild_id:
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
await self.discover_application_commands(
data=data,
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
if register_new:
await self.register_new_application_commands(data=data, guild_id=guild_id)
_log.debug("Command sync with Guild %s finished.", guild_id)
async def discover_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
) -> None:
"""|coro|
Associates existing, deletes unknown, and updates modified commands for either global commands or a specific
guild. This does a deep check on found commands, which may be expensive CPU-wise.
Running this for global or the same guild multiple times at once may cause unexpected or unstable behavior.
Parameters
----------
data: Optional[List[:class:`dict]]
Payload from ``HTTPClient.get_guild_commands`` or ``HTTPClient.get_global_commands`` to deploy with. If None,
the payload will be retrieved from Discord.
guild_id: Optional[:class:`int`]
Guild ID to deploy application commands to. If ``None``, global commands are deployed to.
associate_known: :class:`bool`
If True, commands on Discord that pass a signature check and a deep check will be associated with locally
added ApplicationCommand objects.
delete_unknown: :class:`bool`
If ``True``, commands on Discord that fail a signature check will be removed. If ``update_known`` is False,
commands that pass the signature check but fail the deep check will also be removed.
update_known: :class:`bool`
If ``True``, commands on Discord that pass a signature check but fail the deep check will be updated.
"""
if not associate_known and not delete_unknown and not update_known:
# If everything is disabled, there is no point in doing anything.
return
if self.application_id is None:
raise NotImplementedError("Could not get the current application id")
if not data:
if guild_id:
# we do not care about typeddict specificity here
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
for raw_response in data:
payload_type = raw_response["type"] if "type" in raw_response else 1
fixed_guild_id = raw_response.get("guild_id", None)
response_signature = {
"type": int(payload_type),
"qualified_name": raw_response["name"],
"guild_id": None if not fixed_guild_id else int(fixed_guild_id),
}
app_cmd = self.get_application_command_from_signature(**response_signature)
if app_cmd:
if not isinstance(app_cmd, BaseApplicationCommand):
raise ValueError(
(
f".get_application_command_from_signature with kwargs: {response_signature} "
f"returned {type(app_cmd)} but BaseApplicationCommand was expected."
)
)
if app_cmd.is_payload_valid(raw_response, guild_id):
if associate_known:
_log.debug(
"nextcord.ConnectionState: Command with signature %s associated with added command.",
response_signature,
)
app_cmd.parse_discord_response(self, raw_response)
self.add_application_command(app_cmd, use_rollout=True)
elif update_known:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, updating.",
response_signature,
)
await self.register_application_command(app_cmd, guild_id)
elif delete_unknown:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, removing.",
response_signature,
)
# TODO: Re-examine how worthwhile this is.
await self.delete_application_command(app_cmd, guild_id)
elif delete_unknown:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, removing.",
response_signature,
)
if guild_id:
await self.http.delete_guild_command(
self.application_id, guild_id, raw_response["id"]
)
else:
await self.http.delete_global_command(self.application_id, raw_response["id"])
async def deploy_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
*,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
) -> None:
warnings.warn(
".deploy_application_commands is deprecated, use .discover_application_commands instead.",
stacklevel=2,
category=FutureWarning,
)
await self.discover_application_commands(
data=data,
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
async def associate_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".associate_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=True,
delete_unknown=False,
update_known=False,
)
async def delete_unknown_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".delete_unknown_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=False,
delete_unknown=True,
update_known=False,
)
async def update_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".update_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=False,
delete_unknown=False,
update_known=True,
)
async def register_new_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
"""|coro|
Registers locally added application commands that don't match a signature that Discord has registered for
either global commands or a specific guild.
Parameters
----------
data: Optional[List[:class:`dict`]]
Data to use when comparing local application commands to what Discord has. Should be a list of application
command data from Discord. If left as ``None``, it will be fetched if needed. Defaults to ``None``
guild_id: Optional[:class:`int`]
ID of the guild to sync application commands with. If set to ``None``, global commands will be synced instead.
Defaults to ``None``.
"""
if not data:
if self.application_id is None:
raise TypeError("Could not get the current application id")
if guild_id:
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
data_signatures = [
(
raw_response["name"],
int(raw_response["type"] if "type" in raw_response else 1),
int(temp) if (temp := raw_response.get("guild_id", None)) else temp,
)
for raw_response in data
]
# add_application_command can change the size of the dictionary, and apparently .items() doesn't prevent that
# "RuntimeError: dictionary changed size during iteration" from happening. So a copy is made for just this.
for signature, app_cmd in self._application_command_signatures.copy().items():
if (
signature not in data_signatures and signature[2] == guild_id
): # index 2 of the tuple is the guild ID.
await self.register_application_command(app_cmd, guild_id)
async def register_application_command(
self, command: BaseApplicationCommand, guild_id: Optional[int] = None
) -> None:
"""|coro|
Registers the given application command either for a specific guild or globally and adds the command to the bot.
Parameters
----------
command: :class:`BaseApplicationCommand`
Application command to register.
guild_id: Optional[:class:`int`]
ID of the guild to register the application commands to. If set to ``None``, the commands will be registered
as global commands instead. Defaults to ``None``.
"""
payload: EditApplicationCommand = command.get_payload(guild_id) # type: ignore
_log.info(
"nextcord.ConnectionState: Registering command with signature %s",
command.get_signature(guild_id),
)
if self.application_id is None:
raise TypeError("Could not get the current application's id")
try:
if guild_id:
raw_response = await self.http.upsert_guild_command(
self.application_id, guild_id, payload
)
else:
raw_response = await self.http.upsert_global_command(self.application_id, payload)
except Exception as e:
_log.error("Error registering command %s: %s", command.error_name, e)
raise e
command.parse_discord_response(self, raw_response)
self.add_application_command(command, pre_remove=False)
async def delete_application_command(
self, command: BaseApplicationCommand, guild_id: Optional[int] = None
) -> None:
"""|coro|
Deletes the given application from Discord for the given guild ID or globally, then removes the signature and
command ID from the cache if possible.
Parameters
----------
command: :class:`ApplicationCommand`
Application command to delete.
guild_id: Optional[:class:`int`]
Guild ID to delete the application commands from. If ``None``, the command is deleted from global.
"""
if self.application_id is None:
raise NotImplementedError("Could not get the current application id")
try:
if guild_id:
await self.http.delete_guild_command(
self.application_id, guild_id, command.command_ids[guild_id]
)
else:
await self.http.delete_global_command(
self.application_id, command.command_ids[guild_id]
)
self._application_command_ids.pop(command.command_ids[guild_id], None)
self._application_command_signatures.pop(command.get_signature(guild_id), None)
except KeyError as e:
if guild_id:
_log.error(
"Could not globally unregister command %s "
"as it is not registered in the provided guild.",
command.error_name,
)
raise KeyError(
"This command cannot be globally unregistered, "
"as it is not registered in the provided guild."
) from e
_log.error(
"Could not globally unregister command %s as it is not a global command.",
command.error_name,
)
raise KeyError(
"This command cannot be globally unregistered, as it is not a global command."
) from e
except Exception as e:
_log.error("Error unregistering command %s: %s", command.error_name, e)
raise e
# async def register_bulk_application_commands(self) -> None:
# # TODO: Using Bulk upsert seems to delete all commands
# # It might be good to keep this around as a reminder for future work. Bulk upsert seem to delete everything
# # that isn't part of that bulk upsert, for both global and guild commands. While useful, this will
# # update/overwrite existing commands, which may (needs testing) wipe out all permissions associated with those
# # commands. Look for an opportunity to use bulk upsert.
# raise NotImplementedError
async def chunker(
self,
guild_id: int,
query: str = "",
limit: int = 0,
presences: bool = False,
*,
nonce: Optional[str] = None,
) -> None:
ws = self._get_websocket(guild_id) # This is ignored upstream
await ws.request_chunks(
guild_id, query=query, limit=limit, presences=presences, nonce=nonce
)
async def query_members(
self,
guild: Guild,
query: Optional[str],
limit: int,
user_ids: Optional[List[int]],
cache: bool,
presences: bool,
) -> List[Member]:
guild_id = guild.id
ws = self._get_websocket(guild_id)
if ws is None: # pyright: ignore[reportUnnecessaryComparison]
raise RuntimeError("Somehow do not have a websocket for this guild_id")
request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache)
self._chunk_requests[request.nonce] = request
try:
# start the query operation
await ws.request_chunks(
guild_id,
query=query,
limit=limit,
user_ids=user_ids,
presences=presences,
nonce=request.nonce,
)
return await asyncio.wait_for(request.wait(), timeout=30.0)
except asyncio.TimeoutError:
_log.warning(
"Timed out waiting for chunks with query %r and limit %d for guild_id %d",
query,
limit,
guild_id,
)
raise
async def _delay_ready(self) -> None:
try:
states = []
while True:
# this snippet of code is basically waiting N seconds
# until the last GUILD_CREATE was sent
try:
guild = await asyncio.wait_for(
self._ready_state.get(), timeout=self.guild_ready_timeout
)
except asyncio.TimeoutError:
break
else:
if self._guild_needs_chunking(guild):
future = await self.chunk_guild(guild, wait=False)
states.append((guild, future))
elif guild.unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
for guild, future in states:
try:
await asyncio.wait_for(future, timeout=5.0)
except asyncio.TimeoutError:
_log.warning(
"Shard ID %s timed out waiting for chunks for guild_id %s.",
guild.shard_id,
guild.id,
)
if guild.unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
# remove the state
# AttributeError: already been deleted somehow
with contextlib.suppress(AttributeError):
del self._ready_state
except asyncio.CancelledError:
pass
else:
# dispatch the event
self.call_handlers("ready")
self.dispatch("ready")
finally:
self._ready_task = None
def parse_ready(self, data) -> None:
if self._ready_task is not None:
self._ready_task.cancel()
self._ready_state = asyncio.Queue()
self.clear(views=False)
self.user = ClientUser(state=self, data=data["user"])
self.store_user(data["user"])
if self.application_id is None:
try:
application = data["application"]
except KeyError:
pass
else:
self.application_id = utils.get_as_snowflake(application, "id")
# flags will always be present here
self.application_flags = ApplicationFlags._from_value(application["flags"])
for guild_data in data["guilds"]:
self._add_guild_from_data(guild_data)
self.dispatch("connect")
self._ready_task = asyncio.create_task(self._delay_ready())
def parse_resumed(self, data) -> None:
self.dispatch("resumed")
def parse_message_create(self, data) -> None:
channel, _ = self._get_guild_channel(data)
# channel would be the correct type here
message = Message(channel=channel, data=data, state=self) # type: ignore
self.dispatch("message", message)
if self._messages is not None:
self._messages.append(message)
# we ensure that the channel is either a TextChannel, ForumChannel, Thread or VoiceChannel
if channel and channel.__class__ in (TextChannel, ForumChannel, Thread, VoiceChannel):
channel.last_message_id = message.id # type: ignore
def parse_message_delete(self, data) -> None:
raw = RawMessageDeleteEvent(data)
found = self._get_message(raw.message_id)
raw.cached_message = found
self.dispatch("raw_message_delete", raw)
if self._messages is not None and found is not None:
self.dispatch("message_delete", found)
self._messages.remove(found)
def parse_message_delete_bulk(self, data) -> None:
raw = RawBulkMessageDeleteEvent(data)
if self._messages:
found_messages = [
message for message in self._messages if message.id in raw.message_ids
]
else:
found_messages = []
raw.cached_messages = found_messages
self.dispatch("raw_bulk_message_delete", raw)
if found_messages:
self.dispatch("bulk_message_delete", found_messages)
for msg in found_messages:
# self._messages won't be None here
self._messages.remove(msg) # type: ignore
def parse_message_update(self, data) -> None:
raw = RawMessageUpdateEvent(data)
message = self._get_message(raw.message_id)
if message is not None:
older_message = copy.copy(message)
raw.cached_message = older_message
self.dispatch("raw_message_edit", raw)
message._update(data)
# Coerce the `after` parameter to take the new updated Member
# ref: #5999
older_message.author = message.author
self.dispatch("message_edit", older_message, message)
else:
self.dispatch("raw_message_edit", raw)
if "components" in data and self._view_store.is_message_tracked(raw.message_id):
self._view_store.update_from_message(raw.message_id, data["components"])
def parse_message_reaction_add(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(
self, id=emoji_id, animated=emoji.get("animated", False), name=emoji["name"]
)
raw = RawReactionActionEvent(data, emoji, "REACTION_ADD")
member_data = data.get("member")
if member_data:
guild = self._get_guild(raw.guild_id)
if guild is not None:
raw.member = Member(data=member_data, guild=guild, state=self)
else:
raw.member = None
else:
raw.member = None
self.dispatch("raw_reaction_add", raw)
# rich interface here
message = self._get_message(raw.message_id)
if message is not None:
emoji = self._upgrade_partial_emoji(emoji)
reaction = message._add_reaction(data, emoji, raw.user_id)
user = raw.member or self._get_reaction_user(message.channel, raw.user_id)
if user:
self.dispatch("reaction_add", reaction, user)
def parse_message_reaction_remove_all(self, data) -> None:
raw = RawReactionClearEvent(data)
self.dispatch("raw_reaction_clear", raw)
message = self._get_message(raw.message_id)
if message is not None:
old_reactions = message.reactions.copy()
message.reactions.clear()
self.dispatch("reaction_clear", message, old_reactions)
def parse_message_reaction_remove(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji["name"])
raw = RawReactionActionEvent(data, emoji, "REACTION_REMOVE")
self.dispatch("raw_reaction_remove", raw)
message = self._get_message(raw.message_id)
if message is not None:
emoji = self._upgrade_partial_emoji(emoji)
try:
reaction = message._remove_reaction(data, emoji, raw.user_id)
except (AttributeError, ValueError): # eventual consistency lol
pass
else:
user = self._get_reaction_user(message.channel, raw.user_id)
if user:
self.dispatch("reaction_remove", reaction, user)
def parse_message_reaction_remove_emoji(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji["name"])
raw = RawReactionClearEmojiEvent(data, emoji)
self.dispatch("raw_reaction_clear_emoji", raw)
message = self._get_message(raw.message_id)
if message is not None:
try:
reaction = message._clear_emoji(emoji)
except (AttributeError, ValueError): # eventual consistency lol
pass
else:
if reaction:
self.dispatch("reaction_clear_emoji", reaction)
def parse_interaction_create(self, data) -> None:
interaction = self._get_client().get_interaction(data=data)
if data["type"] == 3: # interaction component
custom_id = interaction.data["custom_id"] # type: ignore
component_type = interaction.data["component_type"] # type: ignore
self._view_store.dispatch(component_type, custom_id, interaction)
if data["type"] == 5: # modal submit
custom_id = interaction.data["custom_id"] # type: ignore
# key exists if type is 5 etc
self._modal_store.dispatch(custom_id, interaction)
self.dispatch("interaction", interaction)
def parse_presence_update(self, data) -> None:
guild_id = utils.get_as_snowflake(data, "guild_id")
# guild_id won't be None here
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("PRESENCE_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id)
return
user = data["user"]
member_id = int(user["id"])
member = guild.get_member(member_id)
if member is None:
_log.debug(
"PRESENCE_UPDATE referencing an unknown member ID: %s. Discarding", member_id
)
return
old_member = Member._copy(member)
user_update = member._presence_update(data=data, user=user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
self.dispatch("presence_update", old_member, member)
def parse_user_update(self, data) -> None:
# self.user is *always* cached when this is called
user: ClientUser = self.user # type: ignore
user._update(data)
ref = self._users.get(user.id)
if ref:
ref._update(data)
def parse_invite_create(self, data) -> None:
invite = Invite.from_gateway(state=self, data=data)
self.dispatch("invite_create", invite)
def parse_invite_delete(self, data) -> None:
invite = Invite.from_gateway(state=self, data=data)
self.dispatch("invite_delete", invite)
def parse_channel_delete(self, data) -> None:
guild = self._get_guild(utils.get_as_snowflake(data, "guild_id"))
channel_id = int(data["id"])
if guild is not None:
channel = guild.get_channel(channel_id)
if channel is not None:
guild._remove_channel(channel)
self.dispatch("guild_channel_delete", channel)
def parse_channel_update(self, data) -> None:
channel_type = try_enum(ChannelType, data.get("type"))
channel_id = int(data["id"])
if channel_type is ChannelType.group:
channel = self._get_private_channel(channel_id)
old_channel = copy.copy(channel)
# the channel is a GroupChannel
channel._update_group(data) # type: ignore
self.dispatch("private_channel_update", old_channel, channel)
return
guild_id = utils.get_as_snowflake(data, "guild_id")
guild = self._get_guild(guild_id)
if guild is not None:
channel = guild.get_channel(channel_id)
if channel is not None:
old_channel = copy.copy(channel)
channel._update(guild, data)
self.dispatch("guild_channel_update", old_channel, channel)
else:
_log.debug(
"CHANNEL_UPDATE referencing an unknown channel ID: %s. Discarding.", channel_id
)
else:
_log.debug("CHANNEL_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id)
def parse_channel_create(self, data) -> None:
factory, _ = _channel_factory(data["type"])
if factory is None:
_log.debug(
"CHANNEL_CREATE referencing an unknown channel type %s. Discarding.", data["type"]
)
return
guild_id = utils.get_as_snowflake(data, "guild_id")
guild = self._get_guild(guild_id)
if guild is not None:
# the factory can't be a DMChannel or GroupChannel here
channel = factory(guild=guild, state=self, data=data) # type: ignore
guild._add_channel(channel) # type: ignore
self.dispatch("guild_channel_create", channel)
else:
_log.debug("CHANNEL_CREATE referencing an unknown guild ID: %s. Discarding.", guild_id)
return
def parse_channel_pins_update(self, data) -> None:
channel_id = int(data["channel_id"])
try:
guild = self._get_guild(int(data["guild_id"]))
except KeyError:
guild = None
channel = self._get_private_channel(channel_id)
else:
channel = guild and guild._resolve_channel(channel_id)
if channel is None:
_log.debug(
"CHANNEL_PINS_UPDATE referencing an unknown channel ID: %s. Discarding.", channel_id
)
return
last_pin = (
utils.parse_time(data["last_pin_timestamp"]) if data["last_pin_timestamp"] else None
)
if guild is None:
self.dispatch("private_channel_pins_update", channel, last_pin)
else:
self.dispatch("guild_channel_pins_update", channel, last_pin)
def parse_thread_create(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_CREATE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread = Thread(guild=guild, state=guild._state, data=data)
has_thread = guild.get_thread(thread.id)
guild._add_thread(thread)
if not has_thread:
# `newly_created` is documented outside of a thread's fields:
# https://discord.dev/topics/gateway-events#thread-create
if data.get("newly_created", False):
if isinstance(thread.parent, ForumChannel):
thread.parent.last_message_id = thread.id
self.dispatch("thread_create", thread)
# Avoid an unnecessary breaking change right now by dispatching `thread_join` for
# threads that were already created.
self.dispatch("thread_join", thread)
def parse_thread_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread_id = int(data["id"])
thread = guild.get_thread(thread_id)
if thread is not None:
old = copy.copy(thread)
thread._update(data)
self.dispatch("thread_update", old, thread)
else:
thread = Thread(guild=guild, state=guild._state, data=data)
guild._add_thread(thread)
self.dispatch("thread_join", thread)
def parse_thread_delete(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_DELETE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread_id = int(data["id"])
thread = guild.get_thread(thread_id)
if thread is not None:
guild._remove_thread(thread)
self.dispatch("thread_delete", thread)
def parse_thread_list_sync(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_LIST_SYNC referencing an unknown guild ID: %s. Discarding", guild_id)
return
try:
channel_ids = set(data["channel_ids"])
except KeyError:
# If not provided, then the entire guild is being synced
# So all previous thread data should be overwritten
previous_threads = guild._threads.copy()
guild._clear_threads()
else:
previous_threads = guild._filter_threads(channel_ids)
threads = {d["id"]: guild._store_thread(d) for d in data.get("threads", [])}
for member in data.get("members", []):
try:
# note: member['id'] is the thread_id
thread = threads[member["id"]]
except KeyError:
continue
else:
thread._add_member(ThreadMember(thread, member))
for thread in threads.values():
old = previous_threads.pop(thread.id, None)
if old is None:
self.dispatch("thread_join", thread)
for thread in previous_threads.values():
self.dispatch("thread_remove", thread)
def parse_thread_member_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug(
"THREAD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id
)
return
thread_id = int(data["id"])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
_log.debug(
"THREAD_MEMBER_UPDATE referencing an unknown thread ID: %s. Discarding", thread_id
)
return
member = ThreadMember(thread, data)
thread.me = member
def parse_thread_members_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug(
"THREAD_MEMBERS_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id
)
return
thread_id = int(data["id"])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
_log.debug(
"THREAD_MEMBERS_UPDATE referencing an unknown thread ID: %s. Discarding", thread_id
)
return
added_members = [ThreadMember(thread, d) for d in data.get("added_members", [])]
removed_member_ids = [int(x) for x in data.get("removed_member_ids", [])]
self_id = self.self_id
for member in added_members:
if member.id != self_id:
thread._add_member(member)
self.dispatch("thread_member_join", member)
else:
thread.me = member
self.dispatch("thread_join", thread)
for member_id in removed_member_ids:
if member_id != self_id:
member = thread._pop_member(member_id)
if member is not None:
self.dispatch("thread_member_remove", member)
else:
self.dispatch("thread_remove", thread)
def parse_guild_member_add(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_MEMBER_ADD referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
member = Member(guild=guild, data=data, state=self)
if self.member_cache_flags.joined:
guild._add_member(member)
with contextlib.suppress(AttributeError):
guild._member_count += 1
self.dispatch("member_join", member)
def parse_guild_member_remove(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
with contextlib.suppress(AttributeError):
guild._member_count -= 1
user_id = int(data["user"]["id"])
member = guild.get_member(user_id)
if member is not None:
guild._remove_member(member)
self.dispatch("member_remove", member)
else:
_log.debug(
(
"GUILD_MEMBER_REMOVE referencing an unknown guild ID: %s."
"Falling back to raw data."
),
data["guild_id"],
)
raw = RawMemberRemoveEvent(data=data, state=self)
self.dispatch("raw_member_remove", raw)
def parse_guild_member_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
user = data["user"]
user_id = int(user["id"])
if guild is None:
_log.debug(
"GUILD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
member = guild.get_member(user_id)
if member is not None:
old_member = Member._copy(member)
member._update(data)
user_update = member._update_inner_user(user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
self.dispatch("member_update", old_member, member)
else:
if self.member_cache_flags.joined:
member = Member(data=data, guild=guild, state=self)
# Force an update on the inner user if necessary
user_update = member._update_inner_user(user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
guild._add_member(member)
_log.debug(
"GUILD_MEMBER_UPDATE referencing an unknown member ID: %s. Discarding.", user_id
)
def parse_guild_emojis_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_EMOJIS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
before_emojis = guild.emojis
for emoji in before_emojis:
self._emojis.pop(emoji.id, None)
guild.emojis = tuple([self.store_emoji(guild, d) for d in data["emojis"]])
self.dispatch("guild_emojis_update", guild, before_emojis, guild.emojis)
def parse_guild_stickers_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_STICKERS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
before_stickers = guild.stickers
for emoji in before_stickers:
self._stickers.pop(emoji.id, None)
guild.stickers = tuple([self.store_sticker(guild, d) for d in data["stickers"]])
self.dispatch("guild_stickers_update", guild, before_stickers, guild.stickers)
def _get_create_guild(self, data):
if data.get("unavailable") is False:
# GUILD_CREATE with unavailable in the response
# usually means that the guild has become available
# and is therefore in the cache
guild = self._get_guild(int(data["id"]))
if guild is not None:
guild.unavailable = False
guild._from_data(data)
return guild
return self._add_guild_from_data(data)
def is_guild_evicted(self, guild) -> bool:
return guild.id not in self._guilds
async def chunk_guild(self, guild, *, wait: bool = True, cache=None):
if cache is None:
cache = self.member_cache_flags.joined
request = self._chunk_requests.get(guild.id)
if request is None:
self._chunk_requests[guild.id] = request = ChunkRequest(
guild.id, self.loop, self._get_guild, cache=cache
)
await self.chunker(guild.id, nonce=request.nonce)
if wait:
return await request.wait()
return request.get_future()
async def _chunk_and_dispatch(self, guild, unavailable) -> None:
try:
await asyncio.wait_for(self.chunk_guild(guild), timeout=60.0)
except asyncio.TimeoutError:
_log.info("Somehow timed out waiting for chunks.")
if unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
def parse_guild_create(self, data) -> None:
unavailable = data.get("unavailable")
if unavailable is True:
# joined a guild with unavailable == True so..
return
guild = self._get_create_guild(data)
try:
# Notify the on_ready state, if any, that this guild is complete.
self._ready_state.put_nowait(guild)
except AttributeError:
pass
else:
# If we're waiting for the event, put the rest on hold
return
# check if it requires chunking
if self._guild_needs_chunking(guild):
task = asyncio.create_task(self._chunk_and_dispatch(guild, unavailable))
self._chunk_tasks[guild.id] = task
task.add_done_callback(lambda _t: self._chunk_tasks.pop(guild.id, None))
return
# Dispatch available if newly available
if unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
def parse_guild_update(self, data) -> None:
guild = self._get_guild(int(data["id"]))
if guild is not None:
old_guild = copy.copy(guild)
guild._from_data(data)
self.dispatch("guild_update", old_guild, guild)
else:
_log.debug("GUILD_UPDATE referencing an unknown guild ID: %s. Discarding.", data["id"])
def parse_guild_delete(self, data) -> None:
guild = self._get_guild(int(data["id"]))
if guild is None:
_log.debug("GUILD_DELETE referencing an unknown guild ID: %s. Discarding.", data["id"])
return
if data.get("unavailable", False):
# GUILD_DELETE with unavailable being True means that the
# guild that was available is now currently unavailable
guild.unavailable = True
self.dispatch("guild_unavailable", guild)
return
# do a cleanup of the messages cache
if self._messages is not None:
self._messages: Optional[Deque[Message]] = deque(
(msg for msg in self._messages if msg.guild != guild), maxlen=self.max_messages
)
self._remove_guild(guild)
self.dispatch("guild_remove", guild)
def parse_guild_ban_add(self, data) -> None:
# we make the assumption that GUILD_BAN_ADD is done
# before GUILD_MEMBER_REMOVE is called
# hence we don't remove it from cache or do anything
# strange with it, the main purpose of this event
# is mainly to dispatch to another event worth listening to for logging
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
try:
user = User(data=data["user"], state=self)
except KeyError:
pass
else:
member = guild.get_member(user.id) or user
self.dispatch("member_ban", guild, member)
def parse_guild_ban_remove(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None and "user" in data:
user = self.store_user(data["user"])
self.dispatch("member_unban", guild, user)
def parse_guild_role_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_ROLE_CREATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
role_data = data["role"]
role = Role(guild=guild, data=role_data, state=self)
guild._add_role(role)
self.dispatch("guild_role_create", role)
def parse_guild_role_delete(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
role_id = int(data["role_id"])
try:
role = guild._remove_role(role_id)
except KeyError:
return
else:
self.dispatch("guild_role_delete", role)
else:
_log.debug(
"GUILD_ROLE_DELETE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_role_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
role_data = data["role"]
role_id = int(role_data["id"])
role = guild.get_role(role_id)
if role is not None:
old_role = copy.copy(role)
role._update(role_data)
self.dispatch("guild_role_update", old_role, role)
else:
_log.debug(
"GUILD_ROLE_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_members_chunk(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
presences = data.get("presences", [])
# the guild won't be None here
members = [Member(guild=guild, data=member, state=self) for member in data.get("members", [])] # type: ignore
_log.debug("Processed a chunk for %s members in guild ID %s.", len(members), guild_id)
if presences:
member_dict = {str(member.id): member for member in members}
for presence in presences:
user = presence["user"]
member_id = user["id"]
member = member_dict.get(member_id)
if member is not None:
member._presence_update(presence, user)
complete = data.get("chunk_index", 0) + 1 == data.get("chunk_count")
self.process_chunk_requests(guild_id, data.get("nonce"), members, complete)
def parse_guild_integrations_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
self.dispatch("guild_integrations_update", guild)
else:
_log.debug(
"GUILD_INTEGRATIONS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_integration_create(self, data) -> None:
guild_id = int(data.pop("guild_id"))
guild = self._get_guild(guild_id)
if guild is not None:
cls, _ = _integration_factory(data["type"])
integration = cls(data=data, guild=guild)
self.dispatch("integration_create", integration)
else:
_log.debug(
"INTEGRATION_CREATE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_integration_update(self, data) -> None:
guild_id = int(data.pop("guild_id"))
guild = self._get_guild(guild_id)
if guild is not None:
cls, _ = _integration_factory(data["type"])
integration = cls(data=data, guild=guild)
self.dispatch("integration_update", integration)
else:
_log.debug(
"INTEGRATION_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_integration_delete(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is not None:
raw = RawIntegrationDeleteEvent(data)
self.dispatch("raw_integration_delete", raw)
else:
_log.debug(
"INTEGRATION_DELETE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_webhooks_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"WEBHOOKS_UPDATE referencing an unknown guild ID: %s. Discarding", data["guild_id"]
)
return
channel = guild.get_channel(int(data["channel_id"]))
if channel is not None:
self.dispatch("webhooks_update", channel)
else:
_log.debug(
"WEBHOOKS_UPDATE referencing an unknown channel ID: %s. Discarding.",
data["channel_id"],
)
def parse_stage_instance_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
stage_instance = StageInstance(guild=guild, state=self, data=data)
guild._stage_instances[stage_instance.id] = stage_instance
self.dispatch("stage_instance_create", stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_CREATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_stage_instance_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
stage_instance = guild._stage_instances.get(int(data["id"]))
if stage_instance is not None:
old_stage_instance = copy.copy(stage_instance)
stage_instance._update(data)
self.dispatch("stage_instance_update", old_stage_instance, stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_UPDATE referencing unknown stage instance ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"STAGE_INSTANCE_UPDATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_stage_instance_delete(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
try:
stage_instance = guild._stage_instances.pop(int(data["id"]))
except KeyError:
pass
else:
self.dispatch("stage_instance_delete", stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_DELETE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_voice_state_update(self, data) -> None:
guild = self._get_guild(utils.get_as_snowflake(data, "guild_id"))
channel_id = utils.get_as_snowflake(data, "channel_id")
flags = self.member_cache_flags
# self.user is *always* cached when this is called
self_id = self.user.id # type: ignore
if guild is not None:
if int(data["user_id"]) == self_id:
voice = self._get_voice_client(guild.id)
if voice is not None:
coro = voice.on_voice_state_update(data)
task = asyncio.create_task(
logging_coroutine(coro, info="Voice Protocol voice state update handler")
)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
member, before, after = guild._update_voice_state(data, channel_id) # type: ignore
after = copy.copy(after)
if member is not None:
if flags.voice:
if channel_id is None and flags._voice_only and member.id != self_id:
# Only remove from cache if we only have the voice flag enabled
# Member doesn't meet the Snowflake protocol currently
guild._remove_member(member)
elif channel_id is not None:
guild._add_member(member)
self.dispatch("voice_state_update", member, before, after)
else:
_log.debug(
"VOICE_STATE_UPDATE referencing an unknown member ID: %s. Discarding.",
data["user_id"],
)
def parse_voice_server_update(self, data) -> None:
try:
key_id = int(data["guild_id"])
except KeyError:
key_id = int(data["channel_id"])
vc = self._get_voice_client(key_id)
if vc is not None:
coro = vc.on_voice_server_update(data)
task = asyncio.create_task(
logging_coroutine(coro, info="Voice Protocol voice server update handler")
)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
def parse_typing_start(self, data) -> None:
raw = RawTypingEvent(data)
member_data = data.get("member")
if member_data:
guild = self._get_guild(raw.guild_id)
if guild is not None:
raw.member = Member(data=member_data, guild=guild, state=self)
else:
raw.member = None
else:
raw.member = None
self.dispatch("raw_typing", raw)
channel, guild = self._get_guild_channel(data)
if channel is not None: # pyright: ignore[reportUnnecessaryComparison]
user = raw.member or self._get_typing_user(channel, raw.user_id) # type: ignore
# will be messageable channel if we get here
if user is not None:
self.dispatch("typing", channel, user, raw.when)
def _get_typing_user(
self, channel: Optional[MessageableChannel], user_id: int
) -> Optional[Union[User, Member]]:
if isinstance(channel, DMChannel):
return channel.recipient or self.get_user(user_id)
if isinstance(channel, (Thread, TextChannel)):
return channel.guild.get_member(user_id)
if isinstance(channel, GroupChannel):
return utils.find(lambda x: x.id == user_id, channel.recipients)
return self.get_user(user_id)
def _get_reaction_user(
self, channel: MessageableChannel, user_id: int
) -> Optional[Union[User, Member]]:
if isinstance(channel, TextChannel):
return channel.guild.get_member(user_id)
return self.get_user(user_id)
def get_reaction_emoji(self, data) -> Union[Emoji, PartialEmoji]:
emoji_id = utils.get_as_snowflake(data, "id")
if not emoji_id:
return data["name"]
try:
return self._emojis[emoji_id]
except KeyError:
return PartialEmoji.with_state(
self, animated=data.get("animated", False), id=emoji_id, name=data["name"]
)
def _upgrade_partial_emoji(self, emoji: PartialEmoji) -> Union[Emoji, PartialEmoji, str]:
emoji_id = emoji.id
if not emoji_id:
return emoji.name
try:
return self._emojis[emoji_id]
except KeyError:
return emoji
def get_channel(self, id: Optional[int]) -> Optional[Union[Channel, Thread]]:
if id is None:
return None
pm = self._get_private_channel(id)
if pm is not None:
return pm
for guild in self.guilds:
channel = guild._resolve_channel(id)
if channel is not None:
return channel
return None
def get_scheduled_event(self, id: int) -> Optional[ScheduledEvent]:
for guild in self.guilds:
if event := guild.get_scheduled_event(id):
return event
return None
def create_message(
self,
*,
channel: MessageableChannel,
data: MessagePayload,
) -> Message:
return Message(state=self, channel=channel, data=data)
def create_scheduled_event(
self, *, guild: Guild, data: ScheduledEventPayload
) -> ScheduledEvent:
return ScheduledEvent(state=self, guild=guild, data=data)
def parse_guild_scheduled_event_create(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
event = self.create_scheduled_event(guild=guild, data=data)
guild._add_scheduled_event(event)
self.dispatch("guild_scheduled_event_create", event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_CREATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_update(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["id"])):
old = copy.copy(event)
event._update(data)
self.dispatch("guild_scheduled_event_update", old, event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_UPDATE referencing unknown event ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_UPDATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_delete(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["id"])):
guild._remove_scheduled_event(event.id)
self.dispatch("guild_scheduled_event_delete", event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_DELETE referencing unknown event ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_DELETE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_user_add(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["guild_scheduled_event_id"])):
u = ScheduledEventUser.from_id(
event=event, user_id=int(data["user_id"]), state=self
)
event._add_user(u)
self.dispatch("guild_scheduled_event_user_add", event, u)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_ADD referencing unknown"
" event ID: %s. Discarding.",
data["user_id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_ADD referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_user_remove(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["guild_scheduled_event_id"])):
event._remove_user(int(data["user_id"]))
self.dispatch(
"guild_scheduled_event_user_remove",
event,
ScheduledEventUser.from_id(
event=event, user_id=int(data["user_id"]), state=self
),
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_REMOVE referencing unknown"
" event ID: %s. Discarding.",
data["user_id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_REMOVE referencing unknown"
" guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_auto_moderation_rule_create(self, data) -> None:
self.dispatch(
"auto_moderation_rule_create",
AutoModerationRule(data=data, state=self),
)
def parse_auto_moderation_rule_update(self, data) -> None:
self.dispatch("auto_moderation_rule_update", AutoModerationRule(data=data, state=self))
def parse_auto_moderation_rule_delete(self, data) -> None:
self.dispatch("auto_moderation_rule_delete", AutoModerationRule(data=data, state=self))
def parse_auto_moderation_action_execution(self, data) -> None:
self.dispatch(
"auto_moderation_action_execution", AutoModerationActionExecution(data=data, state=self)
)
def parse_guild_audit_log_entry_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
user_id = None if data.get("user_id") is None else int(data["user_id"])
user = self.get_user(user_id)
users = {} if user_id is None or user is None else {user_id: user}
if guild is not None:
entry = AuditLogEntry(auto_moderation_rules={}, users=users, data=data, guild=guild)
self.dispatch("guild_audit_log_entry_create", entry)
else:
_log.debug(
"guild_audit_log_entry_create wasn't dispatched because the guild (%r) and/or user (%r) are None!",
guild,
user,
)
The provided code snippet includes necessary dependencies for implementing the `get_messages_from_interaction` function. Write a Python function `def get_messages_from_interaction( state: ConnectionState, interaction: Interaction ) -> List[Message]` to solve the following problem:
Tries to get a list of resolved :class:`Message` objects from the interaction data. Parameters ---------- state: :class:`ConnectionState` State object to construct messages with. interaction: :class:`Interaction` Interaction object to attempt to get resolved messages from. Returns ------- List[:class:`Message`] A list of resolved messages.
Here is the function:
def get_messages_from_interaction(
state: ConnectionState, interaction: Interaction
) -> List[Message]:
"""Tries to get a list of resolved :class:`Message` objects from the interaction data.
Parameters
----------
state: :class:`ConnectionState`
State object to construct messages with.
interaction: :class:`Interaction`
Interaction object to attempt to get resolved messages from.
Returns
-------
List[:class:`Message`]
A list of resolved messages.
"""
data = interaction.data
ret = []
data = cast(ApplicationCommandInteractionData, data)
if "resolved" in data and "messages" in data["resolved"]:
message_payloads = data["resolved"]["messages"]
for msg_id, msg_payload in message_payloads.items():
if not (message := state._get_message(int(msg_id))):
message = Message(channel=interaction.channel, data=msg_payload, state=state) # type: ignore # interaction.channel can be VoiceChannel somehow
ret.append(message)
return ret | Tries to get a list of resolved :class:`Message` objects from the interaction data. Parameters ---------- state: :class:`ConnectionState` State object to construct messages with. interaction: :class:`Interaction` Interaction object to attempt to get resolved messages from. Returns ------- List[:class:`Message`] A list of resolved messages. |
160,991 | from __future__ import annotations
import asyncio
import contextlib
import logging
import sys
import warnings
from inspect import Parameter, signature
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Coroutine,
Dict,
Iterable,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
import typing_extensions
from typing_extensions import Annotated
from .abc import GuildChannel
from .channel import (
CategoryChannel,
DMChannel,
ForumChannel,
GroupChannel,
StageChannel,
TextChannel,
VoiceChannel,
)
from .enums import ApplicationCommandOptionType, ApplicationCommandType, ChannelType, Locale
from .errors import (
ApplicationCheckFailure,
ApplicationCommandOptionMissing,
ApplicationError,
ApplicationInvokeError,
)
from .guild import Guild
from .interactions import Interaction
from .member import Member
from .message import Attachment, Message
from .object import Object
from .permissions import Permissions
from .role import Role
from .threads import Thread
from .types.interactions import ApplicationCommandInteractionData
from .user import User
from .utils import MISSING, find, maybe_coroutine, parse_docstring
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class Role(Hashable):
"""Represents a Discord role in a :class:`Guild`.
.. container:: operations
.. describe:: x == y
Checks if two roles are equal.
.. describe:: x != y
Checks if two roles are not equal.
.. describe:: x > y
Checks if a role is higher than another in the hierarchy.
.. describe:: x < y
Checks if a role is lower than another in the hierarchy.
.. describe:: x >= y
Checks if a role is higher or equal to another in the hierarchy.
.. describe:: x <= y
Checks if a role is lower or equal to another in the hierarchy.
.. describe:: hash(x)
Return the role's hash.
.. describe:: str(x)
Returns the role's name.
Attributes
----------
id: :class:`int`
The ID for the role.
name: :class:`str`
The name of the role.
guild: :class:`Guild`
The guild the role belongs to.
hoist: :class:`bool`
Indicates if the role will be displayed separately from other members.
position: :class:`int`
The position of the role. This number is usually positive. The bottom
role has a position of 0.
.. warning::
Multiple roles can have the same position number. As a consequence
of this, comparing via role position is prone to subtle bugs if
checking for role hierarchy. The recommended and correct way to
compare for roles in the hierarchy is using the comparison
operators on the role objects themselves.
managed: :class:`bool`
Indicates if the role is managed by the guild through some form of
integrations such as Twitch.
mentionable: :class:`bool`
Indicates if the role can be mentioned by users.
tags: Optional[:class:`RoleTags`]
The role tags associated with this role.
"""
__slots__ = (
"id",
"name",
"_permissions",
"_colour",
"position",
"managed",
"mentionable",
"hoist",
"guild",
"tags",
"_icon",
"_state",
"_flags",
)
def __init__(self, *, guild: Guild, state: ConnectionState, data: RolePayload) -> None:
self.guild: Guild = guild
self._state: ConnectionState = state
self.id: int = int(data["id"])
self._update(data)
def __str__(self) -> str:
return self.name
def __repr__(self) -> str:
return f"<Role id={self.id} name={self.name!r}>"
def __lt__(self, other: Self) -> bool:
if not isinstance(other, Role) or not isinstance(self, Role):
return NotImplemented
if self.guild != other.guild:
raise RuntimeError("Cannot compare roles from two different guilds.")
# the @everyone role is always the lowest role in hierarchy
guild_id = self.guild.id
if self.id == guild_id:
# everyone_role < everyone_role -> False
return other.id != guild_id
if self.position < other.position:
return True
if self.position == other.position:
return int(self.id) > int(other.id)
return False
def __le__(self, other: Self) -> bool:
r = Role.__lt__(other, self)
if r is NotImplemented:
return NotImplemented
return not r
def __gt__(self, other: Self) -> bool:
return Role.__lt__(other, self)
def __ge__(self, other: Self) -> bool:
r = Role.__lt__(self, other)
if r is NotImplemented:
return NotImplemented
return not r
def _update(self, data: RolePayload) -> None:
self.name: str = data["name"]
self._permissions: int = int(data.get("permissions", 0))
self.position: int = data.get("position", 0)
self._colour: int = data.get("color", 0)
self.hoist: bool = data.get("hoist", False)
self.managed: bool = data.get("managed", False)
self.mentionable: bool = data.get("mentionable", False)
self._icon: Optional[str] = data.get("icon", None)
if self._icon is None:
self._icon: Optional[str] = data.get("unicode_emoji", None)
self.tags: Optional[RoleTags]
try:
self.tags = RoleTags(data["tags"])
except KeyError:
self.tags = None
self._flags: int = data.get("flags", 0)
def is_default(self) -> bool:
""":class:`bool`: Checks if the role is the default role."""
return self.guild.id == self.id
def is_bot_managed(self) -> bool:
""":class:`bool`: Whether the role is associated with a bot.
.. versionadded:: 1.6
"""
return self.tags is not None and self.tags.is_bot_managed()
def is_premium_subscriber(self) -> bool:
""":class:`bool`: Whether the role is the premium subscriber, AKA "boost", role for the guild.
.. versionadded:: 1.6
"""
return self.tags is not None and self.tags.is_premium_subscriber()
def is_integration(self) -> bool:
""":class:`bool`: Whether the role is managed by an integration.
.. versionadded:: 1.6
"""
return self.tags is not None and self.tags.is_integration()
def is_assignable(self) -> bool:
""":class:`bool`: Whether the role is able to be assigned or removed by the bot.
.. versionadded:: 2.0
"""
me = self.guild.me
return (
not self.is_default()
and not self.managed
and (me.top_role > self or me.id == self.guild.owner_id)
)
def is_in_prompt(self) -> bool:
""":class:`bool`: Whether the role can be selected in an onboarding prompt.
.. versionadded:: 2.6
"""
return self.flags.in_prompt
def permissions(self) -> Permissions:
""":class:`Permissions`: Returns the role's permissions."""
return Permissions(self._permissions)
def colour(self) -> Colour:
""":class:`Colour`: Returns the role colour. An alias exists under ``color``."""
return Colour(self._colour)
def color(self) -> Colour:
""":class:`Colour`: Returns the role color. An alias exists under ``colour``."""
return self.colour
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the role's creation time in UTC."""
return snowflake_time(self.id)
def mention(self) -> str:
""":class:`str`: Returns a string that allows you to mention a role."""
if self.id != self.guild.id:
return f"<@&{self.id}>"
return "@everyone"
def members(self) -> List[Member]:
"""List[:class:`Member`]: Returns all the members with this role."""
all_members = self.guild.members
if self.is_default():
return all_members
role_id = self.id
return [member for member in all_members if member._roles.has(role_id)]
def icon(self) -> Optional[Union[Asset, str]]:
"""Optional[Union[:class:`Asset`, :class:`str`]]: Returns the role's icon asset or its
unicode emoji, if available."""
if self._icon is None:
return None
if len(self._icon) == 1:
return self._icon
return Asset._from_icon(self._state, self.id, self._icon, "role")
async def _move(self, position: int, reason: Optional[str]) -> None:
if position <= 0:
raise InvalidArgument("Cannot move role to position 0 or below")
if self.is_default():
raise InvalidArgument("Cannot move default role")
if self.position == position:
return # Save discord the extra request.
http = self._state.http
change_range = range(min(self.position, position), max(self.position, position) + 1)
roles = [
r.id for r in self.guild.roles[1:] if r.position in change_range and r.id != self.id
]
if self.position > position:
roles.insert(0, self.id)
else:
roles.append(self.id)
payload: List[RolePositionUpdate] = [
{"id": z[0], "position": z[1]} for z in zip(roles, change_range)
]
await http.move_role_position(self.guild.id, payload, reason=reason)
async def edit(
self,
*,
name: str = MISSING,
permissions: Permissions = MISSING,
colour: Union[Colour, int] = MISSING,
color: Union[Colour, int] = MISSING,
hoist: bool = MISSING,
mentionable: bool = MISSING,
position: int = MISSING,
reason: Optional[str] = MISSING,
icon: Optional[Union[str, bytes, Asset, Attachment, File]] = MISSING,
) -> Optional[Role]:
"""|coro|
Edits the role.
You must have the :attr:`~Permissions.manage_roles` permission to
use this.
All fields are optional.
.. versionchanged:: 1.4
Can now pass ``int`` to ``colour`` keyword-only parameter.
.. versionchanged:: 2.0
Edits are no longer in-place, the newly edited role is returned instead.
.. versionchanged:: 2.1
The ``icon`` parameter now accepts :class:`Attachment`, and :class:`Asset`.
Parameters
----------
name: :class:`str`
The new role name to change to.
permissions: :class:`Permissions`
The new permissions to change to.
colour: Union[:class:`Colour`, :class:`int`]
The new colour to change to. (aliased to color as well)
hoist: :class:`bool`
Indicates if the role should be shown separately in the member list.
mentionable: :class:`bool`
Indicates if the role should be mentionable by others.
position: :class:`int`
The new role's position. This must be below your top role's
position or it will fail.
icon: Optional[Union[:class:`str`, :class:`bytes`, :class:`File`, :class:`Asset`, :class:`Attachment`]]
The role's icon image
reason: Optional[:class:`str`]
The reason for editing this role. Shows up on the audit log.
Raises
------
Forbidden
You do not have permissions to change the role.
HTTPException
Editing the role failed.
InvalidArgument
An invalid position was given or the default
role was asked to be moved.
Returns
-------
:class:`Role`
The newly edited role.
"""
if position is not MISSING:
await self._move(position, reason=reason)
payload: Dict[str, Any] = {}
if color is not MISSING:
colour = color
if colour is not MISSING:
if isinstance(colour, int):
payload["color"] = colour
else:
payload["color"] = colour.value
if name is not MISSING:
payload["name"] = name
if permissions is not MISSING:
payload["permissions"] = permissions.value
if hoist is not MISSING:
payload["hoist"] = hoist
if mentionable is not MISSING:
payload["mentionable"] = mentionable
if icon is not MISSING:
if isinstance(icon, str):
payload["unicode_emoji"] = icon
else:
payload["icon"] = await obj_to_base64_data(icon)
data = await self._state.http.edit_role(self.guild.id, self.id, reason=reason, **payload)
return Role(guild=self.guild, data=data, state=self._state)
async def delete(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Deletes the role.
You must have the :attr:`~Permissions.manage_roles` permission to
use this.
Parameters
----------
reason: Optional[:class:`str`]
The reason for deleting this role. Shows up on the audit log.
Raises
------
Forbidden
You do not have permissions to delete the role.
HTTPException
Deleting the role failed.
"""
await self._state.http.delete_role(self.guild.id, self.id, reason=reason)
def flags(self) -> RoleFlags:
""":class:`RoleFlags`: The avaliable flags the role has.
.. versionadded:: 2.6
"""
return RoleFlags._from_value(self._flags)
class ApplicationCommandInteractionData(TypedDict):
id: Snowflake
name: str
type: ApplicationCommandType
options: NotRequired[List[ApplicationCommandInteractionDataOption]]
resolved: NotRequired[ApplicationCommandInteractionDataResolved]
target_id: NotRequired[Snowflake]
class ConnectionState:
if TYPE_CHECKING:
_get_websocket: Callable[..., DiscordWebSocket]
_get_client: Callable[..., Client]
_parsers: Dict[str, Callable[[Dict[str, Any]], None]]
def __init__(
self,
*,
dispatch: Callable,
handlers: Dict[str, Callable],
hooks: Dict[str, Callable],
http: HTTPClient,
loop: asyncio.AbstractEventLoop,
max_messages: Optional[int] = 1000,
application_id: Optional[int] = None,
heartbeat_timeout: float = 60.0,
guild_ready_timeout: float = 2.0,
allowed_mentions: Optional[AllowedMentions] = None,
activity: Optional[BaseActivity] = None,
status: Optional[Status] = None,
intents: Intents = Intents.default(),
chunk_guilds_at_startup: bool = MISSING,
member_cache_flags: MemberCacheFlags = MISSING,
) -> None:
self.loop: asyncio.AbstractEventLoop = loop
self.http: HTTPClient = http
self.max_messages: Optional[int] = max_messages
if self.max_messages is not None and self.max_messages <= 0:
self.max_messages = 1000
self.dispatch: Callable = dispatch
self.handlers: Dict[str, Callable] = handlers
self.hooks: Dict[str, Callable] = hooks
self.shard_count: Optional[int] = None
self._ready_task: Optional[asyncio.Task] = None
self.application_id: Optional[int] = application_id
self.heartbeat_timeout: float = heartbeat_timeout
self.guild_ready_timeout: float = guild_ready_timeout
if self.guild_ready_timeout < 0:
raise ValueError("guild_ready_timeout cannot be negative")
if allowed_mentions is not None and not isinstance(allowed_mentions, AllowedMentions):
raise TypeError("allowed_mentions parameter must be AllowedMentions")
self.allowed_mentions: Optional[AllowedMentions] = allowed_mentions
self._chunk_requests: Dict[Union[int, str], ChunkRequest] = {}
self._chunk_tasks: Dict[Union[int, str], asyncio.Task[None]] = {}
self._background_tasks: Set[asyncio.Task] = set()
if activity is not None:
if not isinstance(activity, BaseActivity):
raise TypeError("activity parameter must derive from BaseActivity.")
raw_activity = activity.to_dict()
else:
raw_activity = activity
raw_status = ("invisible" if status is Status.offline else str(status)) if status else None
if not isinstance(intents, Intents):
raise TypeError(f"intents parameter must be Intent not {type(intents)!r}")
if not intents.guilds:
_log.warning("Guilds intent seems to be disabled. This may cause state related issues.")
if chunk_guilds_at_startup is MISSING:
chunk_guilds_at_startup = intents.members
self._chunk_guilds: bool = chunk_guilds_at_startup
# Ensure these two are set properly
if not intents.members and self._chunk_guilds:
raise ValueError("Intents.members must be enabled to chunk guilds at startup.")
if member_cache_flags is MISSING:
member_cache_flags = MemberCacheFlags.from_intents(intents)
else:
if not isinstance(member_cache_flags, MemberCacheFlags):
raise TypeError(
"member_cache_flags parameter must be MemberCacheFlags "
f"not {type(member_cache_flags)!r}"
)
member_cache_flags._verify_intents(intents)
self.member_cache_flags: MemberCacheFlags = member_cache_flags
self._activity: Optional[ActivityPayload] = raw_activity
self._status: Optional[str] = raw_status
self._intents: Intents = intents
# A set of all application command objects available. Set because duplicates should not exist.
self._application_commands: Set[BaseApplicationCommand] = set()
# A dictionary of all available unique command signatures. Compiled at runtime because needing to iterate
# through all application commands would take far more time. If memory is problematic, perhaps this can go?
self._application_command_signatures: Dict[
Tuple[Optional[str], int, Optional[int]], BaseApplicationCommand
] = {}
# A dictionary of Discord Application Command ID's and the ApplicationCommand object they correspond to.
self._application_command_ids: Dict[int, BaseApplicationCommand] = {}
if not intents.members or member_cache_flags._empty:
self.store_user = self.create_user
self.deref_user = self.deref_user_no_intents
self.parsers = parsers = {}
for attr, func in inspect.getmembers(self):
if attr.startswith("parse_"):
parsers[attr[6:].upper()] = func
self.clear()
def clear(self, *, views: bool = True, modals: bool = True) -> None:
self.user: Optional[ClientUser] = None
# Originally, this code used WeakValueDictionary to maintain references to the
# global user mapping.
# However, profiling showed that this came with two cons:
# 1. The __weakref__ slot caused a non-trivial increase in memory
# 2. The performance of the mapping caused store_user to be a bottleneck.
# Since this is undesirable, a mapping is now used instead with stored
# references now using a regular dictionary with eviction being done
# using __del__. Testing this for memory leaks led to no discernible leaks,
# though more testing will have to be done.
self._users: Dict[int, User] = {}
self._emojis: Dict[int, Emoji] = {}
self._stickers: Dict[int, GuildSticker] = {}
self._guilds: Dict[int, Guild] = {}
# TODO: Why aren't the above and stuff below application_commands declared in __init__?
self._application_commands = set()
# Thought about making these two weakref.WeakValueDictionary's, but the bot could theoretically be holding on
# to them in a dev-defined, which would desync the bot from itself.
self._application_command_signatures = {}
self._application_command_ids = {}
if views:
self._view_store: ViewStore = ViewStore(self)
if modals:
self._modal_store: ModalStore = ModalStore(self)
self._voice_clients: Dict[int, VoiceProtocol] = {}
# LRU of max size 128
self._private_channels: OrderedDict[int, PrivateChannel] = OrderedDict()
# extra dict to look up private channels by user id
self._private_channels_by_user: Dict[int, DMChannel] = {}
if self.max_messages is not None:
self._messages: Optional[Deque[Message]] = deque(maxlen=self.max_messages)
else:
self._messages: Optional[Deque[Message]] = None
def process_chunk_requests(
self, guild_id: int, nonce: Optional[str], members: List[Member], complete: bool
) -> None:
removed = []
for key, request in self._chunk_requests.items():
if request.guild_id == guild_id and request.nonce == nonce:
request.add_members(members)
if complete:
request.done()
removed.append(key)
for key in removed:
del self._chunk_requests[key]
def call_handlers(self, key: str, *args: Any, **kwargs: Any) -> None:
try:
func = self.handlers[key]
except KeyError:
pass
else:
func(*args, **kwargs)
async def call_hooks(self, key: str, *args: Any, **kwargs: Any) -> None:
try:
coro = self.hooks[key]
except KeyError:
pass
else:
await coro(*args, **kwargs)
def self_id(self) -> Optional[int]:
u = self.user
return u.id if u else None
def intents(self) -> Intents:
ret = Intents.none()
ret.value = self._intents.value
return ret
def voice_clients(self) -> List[VoiceProtocol]:
return list(self._voice_clients.values())
def _get_voice_client(self, guild_id: Optional[int]) -> Optional[VoiceProtocol]:
# the keys of self._voice_clients are ints
return self._voice_clients.get(guild_id) # type: ignore
def _add_voice_client(self, guild_id: int, voice: VoiceProtocol) -> None:
self._voice_clients[guild_id] = voice
def _remove_voice_client(self, guild_id: int) -> None:
self._voice_clients.pop(guild_id, None)
def _update_references(self, ws: DiscordWebSocket) -> None:
for vc in self.voice_clients:
vc.main_ws = ws # type: ignore
def store_user(self, data: UserPayload) -> User:
user_id = int(data["id"])
try:
return self._users[user_id]
except KeyError:
user = User(state=self, data=data)
if user.discriminator != "0000":
self._users[user_id] = user
user._stored = True
return user
def deref_user(self, user_id: int) -> None:
self._users.pop(user_id, None)
def create_user(self, data: Union[PartialUserPayload, UserPayload]) -> User:
return User(state=self, data=data)
def deref_user_no_intents(self, user_id: int) -> None:
return
def get_user(self, id: Optional[int]) -> Optional[User]:
# the keys of self._users are ints
return self._users.get(id) # type: ignore
def store_emoji(self, guild: Guild, data: EmojiPayload) -> Emoji:
# the id will be present here
emoji_id = int(data["id"]) # type: ignore
self._emojis[emoji_id] = emoji = Emoji(guild=guild, state=self, data=data)
return emoji
def store_sticker(self, guild: Guild, data: GuildStickerPayload) -> GuildSticker:
sticker_id = int(data["id"])
self._stickers[sticker_id] = sticker = GuildSticker(state=self, data=data)
return sticker
def store_view(self, view: View, message_id: Optional[int] = None) -> None:
self._view_store.add_view(view, message_id)
def store_modal(self, modal: Modal, user_id: Optional[int] = None) -> None:
self._modal_store.add_modal(modal, user_id)
def remove_view(self, view: View, message_id: Optional[int] = None) -> None:
self._view_store.remove_view(view, message_id)
def remove_modal(self, modal: Modal) -> None:
self._modal_store.remove_modal(modal)
def prevent_view_updates_for(self, message_id: Optional[int]) -> Optional[View]:
return self._view_store.remove_message_tracking(message_id) # type: ignore
def all_views(self) -> List[View]:
return self._view_store.all_views()
def views(self, persistent: bool = True) -> List[View]:
return self._view_store.views(persistent)
def guilds(self) -> List[Guild]:
return list(self._guilds.values())
def _get_guild(self, guild_id: Optional[int]) -> Optional[Guild]:
# the keys of self._guilds are ints
return self._guilds.get(guild_id) # type: ignore
def _add_guild(self, guild: Guild) -> None:
self._guilds[guild.id] = guild
def _remove_guild(self, guild: Guild) -> None:
self._guilds.pop(guild.id, None)
for emoji in guild.emojis:
self._emojis.pop(emoji.id, None)
for sticker in guild.stickers:
self._stickers.pop(sticker.id, None)
del guild
def emojis(self) -> List[Emoji]:
return list(self._emojis.values())
def stickers(self) -> List[GuildSticker]:
return list(self._stickers.values())
def get_emoji(self, emoji_id: Optional[int]) -> Optional[Emoji]:
# the keys of self._emojis are ints
return self._emojis.get(emoji_id) # type: ignore
def get_sticker(self, sticker_id: Optional[int]) -> Optional[GuildSticker]:
# the keys of self._stickers are ints
return self._stickers.get(sticker_id) # type: ignore
def private_channels(self) -> List[PrivateChannel]:
return list(self._private_channels.values())
def _get_private_channel(self, channel_id: Optional[int]) -> Optional[PrivateChannel]:
try:
# the keys of self._private_channels are ints
value = self._private_channels[channel_id] # type: ignore
except KeyError:
return None
else:
self._private_channels.move_to_end(channel_id) # type: ignore
return value
def _get_private_channel_by_user(self, user_id: Optional[int]) -> Optional[DMChannel]:
# the keys of self._private_channels are ints
return self._private_channels_by_user.get(user_id) # type: ignore
def _add_private_channel(self, channel: PrivateChannel) -> None:
channel_id = channel.id
self._private_channels[channel_id] = channel
if len(self._private_channels) > 128:
_, to_remove = self._private_channels.popitem(last=False)
if isinstance(to_remove, DMChannel) and to_remove.recipient:
self._private_channels_by_user.pop(to_remove.recipient.id, None)
if isinstance(channel, DMChannel) and channel.recipient:
self._private_channels_by_user[channel.recipient.id] = channel
def add_dm_channel(self, data: DMChannelPayload) -> DMChannel:
# self.user is *always* cached when this is called
channel = DMChannel(me=self.user, state=self, data=data) # type: ignore
self._add_private_channel(channel)
return channel
def _remove_private_channel(self, channel: PrivateChannel) -> None:
self._private_channels.pop(channel.id, None)
if isinstance(channel, DMChannel):
recipient = channel.recipient
if recipient is not None:
self._private_channels_by_user.pop(recipient.id, None)
def _get_message(self, msg_id: Optional[int]) -> Optional[Message]:
return (
utils.find(lambda m: m.id == msg_id, reversed(self._messages))
if self._messages
else None
)
def _add_guild_from_data(self, data: GuildPayload) -> Guild:
guild = Guild(data=data, state=self)
self._add_guild(guild)
return guild
def _guild_needs_chunking(self, guild: Guild) -> bool:
# If presences are enabled then we get back the old guild.large behaviour
return (
self._chunk_guilds
and not guild.chunked
and not (self._intents.presences and not guild.large)
)
def _get_guild_channel(
self, data: MessagePayload
) -> Tuple[Union[Channel, Thread], Optional[Guild]]:
channel_id = int(data["channel_id"])
try:
guild = self._get_guild(int(data["guild_id"]))
except KeyError:
channel = self.get_channel(channel_id)
if channel is None:
channel = DMChannel._from_message(self, channel_id)
guild = getattr(channel, "guild", None)
else:
channel = guild and guild._resolve_channel(channel_id)
return channel or PartialMessageable(state=self, id=channel_id), guild
def application_commands(self) -> Set[BaseApplicationCommand]:
"""Gets a copy of the ApplicationCommand object set. If the original is given out and modified, massive desyncs
may occur. This should be used internally as well if size-changed-during-iteration is a worry.
"""
return self._application_commands.copy()
def get_application_command(self, command_id: int) -> Optional[BaseApplicationCommand]:
return self._application_command_ids.get(command_id, None)
def get_application_command_from_signature(
self,
*,
type: int,
qualified_name: str,
guild_id: Optional[int],
search_localizations: bool = False,
) -> Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]]:
def get_parent_command(name: str, /) -> Optional[BaseApplicationCommand]:
found = self._application_command_signatures.get((name, type, guild_id))
if not search_localizations:
return found
for command in self._application_command_signatures.values():
if command.name_localizations and name in command.name_localizations.values():
found = command
break
return found
def find_children(
parent: Union[BaseApplicationCommand, SlashApplicationSubcommand], name: str, /
) -> Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]]:
children: Dict[str, SlashApplicationSubcommand] = getattr(parent, "children", {})
if not children:
return parent
found = children.get(name)
if not search_localizations:
return found
subcommand: Union[BaseApplicationCommand, SlashApplicationSubcommand]
for subcommand in children.values():
if subcommand.name_localizations and name in subcommand.name_localizations.values():
found = subcommand
break
return found
parent: Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]] = None
if not qualified_name:
return None
if " " not in qualified_name:
return get_parent_command(qualified_name)
for command_name in qualified_name.split(" "):
if parent is None:
parent = get_parent_command(command_name)
else:
parent = find_children(parent, command_name)
return parent
def get_guild_application_commands(
self, guild_id: Optional[int] = None, rollout: bool = False
) -> List[BaseApplicationCommand]:
"""Gets all commands that have the given guild ID. If guild_id is None, all guild commands are returned. if
rollout is True, guild_ids_to_rollout is used.
"""
return [
app_cmd
for app_cmd in self.application_commands
if guild_id is None
or guild_id in app_cmd.guild_ids
or (rollout and guild_id in app_cmd.guild_ids_to_rollout)
]
def get_global_application_commands(
self, rollout: bool = False
) -> List[BaseApplicationCommand]:
"""Gets all commands that are registered globally. If rollout is True, is_global is used."""
return [
app_cmd
for app_cmd in self.application_commands
if (rollout and app_cmd.is_global) or None in app_cmd.command_ids
]
def add_application_command(
self,
command: BaseApplicationCommand,
*,
overwrite: bool = False,
use_rollout: bool = False,
pre_remove: bool = True,
) -> None:
"""Adds the command to the state and updates the state with any changes made to the command.
Removes all existing references, then adds them.
Safe to call multiple times on the same application command.
Parameters
----------
command: :class:`BaseApplicationCommand`
The command to add/update the state with.
overwrite: :class:`bool`
If the library will let you add a command that overlaps with an existing command. Default ``False``.
use_rollout: :class:`bool`
If the command should be added to the state with its rollout guild IDs.
pre_remove: :class:`bool`
If the command should be removed before adding it. This will clear all signatures from storage, including
rollout ones.
"""
if pre_remove:
self.remove_application_command(command)
signature_set = (
command.get_rollout_signatures() if use_rollout else command.get_signatures()
)
for signature in signature_set:
if not overwrite and (
found_command := self._application_command_signatures.get(signature, None)
):
if found_command is not command:
raise ValueError(
f"{command.error_name} You cannot add application commands with duplicate "
f"signatures."
)
# No else because we do not care if the command has its own signature already in.
else:
self._application_command_signatures[signature] = command
for command_id in command.command_ids.values():
# PyCharm flags found_command as it "might be referenced before assignment", but that can't happen due to it
# being in an AND statement.
# noinspection PyUnboundLocalVariable
if (
not overwrite
and (found_command := self._application_command_ids.get(command_id, None))
and found_command is not command
):
raise ValueError(
f"{command.error_name} You cannot add application commands with duplicate IDs."
)
self._application_command_ids[command_id] = command
# TODO: Add the command to guilds. Should it? Check if it does in the Guild add.
self._application_commands.add(command)
def remove_application_command(self, command: BaseApplicationCommand) -> None:
"""Removes the command and all signatures + associated IDs from the state.
Safe to call with commands that aren't in the state.
Parameters
----------
command: :class:`BaseApplicationCommand`
the command to remove from the state.
"""
signature_set = command.get_rollout_signatures()
for signature in signature_set:
self._application_command_signatures.pop(signature, None)
for cmd_id in command.command_ids.values():
self._application_command_ids.pop(cmd_id, None)
self._application_commands.discard(command)
def add_all_rollout_signatures(self) -> None:
"""This adds all command signatures for rollouts to the signature cache."""
for command in self._application_commands:
self.add_application_command(command, use_rollout=True)
async def sync_all_application_commands(
self,
data: Optional[Dict[Optional[int], List[ApplicationCommandPayload]]] = None,
*,
use_rollout: bool = True,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
ignore_forbidden: bool = True,
):
"""|coro|
Syncs all application commands with Discord. Will sync global commands if any commands added are global, and
syncs with all guilds that have an application command targeting them.
This may call Discord many times depending on how different guilds you have local commands for, and how many
commands Discord needs to be updated or added, which may cause your bot to be rate limited or even Cloudflare
banned in VERY extreme cases.
This may incur high CPU usage depending on how many commands you have and how complex they are, which may cause
your bot to halt while it checks local commands against the existing commands that Discord has.
For a more targeted version of this method, see :func:`Client.sync_application_commands`
Parameters
----------
data: Optional[Dict[Optional[:class:`int`], List[:class:`dict`]]]
Data to use when comparing local application commands to what Discord has. The key should be the
:class:`int` guild ID (`None` for global) corresponding to the value list of application command payloads
from Discord. Any guild ID's not provided will be fetched if needed. Defaults to ``None``
use_rollout: :class:`bool`
If the rollout guild IDs of commands should be used. Defaults to ``True``
associate_known: :class:`bool`
If local commands that match a command already on Discord should be associated with each other.
Defaults to ``True``
delete_unknown: :class:`bool`
If commands on Discord that don't match a local command should be deleted. Defaults to ``True``.
update_known: :class:`bool`
If commands on Discord have a basic match with a local command, but don't fully match, should be updated.
Defaults to ``True``
register_new: :class:`bool`
If a local command that doesn't have a basic match on Discord should be added to Discord.
Defaults to ``True``
ignore_forbidden: :class:`bool`
If this command should raise an :class:`errors.Forbidden` exception when the bot encounters a guild where
it doesn't have permissions to view application commands.
Defaults to ``True``
"""
_log.debug("Beginning sync of all application commands.")
self._get_client().add_all_application_commands()
data = {} if data is None else data.copy()
if self.application_id is None:
raise TypeError("Could not get the current application's id")
for app_cmd in self.application_commands:
self.add_application_command(command=app_cmd, use_rollout=use_rollout)
if app_cmd.is_global and None not in data:
data[None] = await self.http.get_global_commands(self.application_id)
_log.debug("Fetched global application command data.")
if app_cmd.is_guild:
for guild_id in app_cmd.guild_ids_to_rollout if use_rollout else app_cmd.guild_ids:
if guild_id not in data:
try:
data[guild_id] = await self.http.get_guild_commands(
self.application_id, guild_id
)
_log.debug(
"Fetched guild application command data for guild ID %s", guild_id
)
except Forbidden as e:
if ignore_forbidden:
_log.warning(
"nextcord.Client: Forbidden error for %s, is the applications.commands "
"Oauth scope enabled? %s",
guild_id,
e,
)
else:
raise e
for guild_id in data:
_log.debug("Running sync for %s", "global" if guild_id is None else f"Guild {guild_id}")
await self.sync_application_commands(
data=data[guild_id],
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
register_new=register_new,
)
async def sync_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
) -> None:
"""|coro|
Syncs the locally added application commands with the Guild corresponding to the given ID, or syncs
global commands if the guild_id is ``None``.
Parameters
----------
data: Optional[List[:class:`dict`]]
Data to use when comparing local application commands to what Discord has. Should be a list of application
command data from Discord. If left as ``None``, it will be fetched if needed. Defaults to ``None``.
guild_id: Optional[:class:`int`]
ID of the guild to sync application commands with. If set to ``None``, global commands will be synced instead.
Defaults to ``None``.
associate_known: :class:`bool`
If local commands that match a command already on Discord should be associated with each other.
Defaults to ``True``.
delete_unknown: :class:`bool`
If commands on Discord that don't match a local command should be deleted. Defaults to ``True``.
update_known: :class:`bool`
If commands on Discord have a basic match with a local command, but don't fully match, should be updated.
Defaults to ``True``.
register_new: :class:`bool`
If a local command that doesn't have a basic match on Discord should be added to Discord.
Defaults to ``True``.
"""
_log.debug("Syncing commands to %s", guild_id)
if self.application_id is None:
raise TypeError("Could not get the current application's id")
if not data:
if guild_id:
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
await self.discover_application_commands(
data=data,
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
if register_new:
await self.register_new_application_commands(data=data, guild_id=guild_id)
_log.debug("Command sync with Guild %s finished.", guild_id)
async def discover_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
) -> None:
"""|coro|
Associates existing, deletes unknown, and updates modified commands for either global commands or a specific
guild. This does a deep check on found commands, which may be expensive CPU-wise.
Running this for global or the same guild multiple times at once may cause unexpected or unstable behavior.
Parameters
----------
data: Optional[List[:class:`dict]]
Payload from ``HTTPClient.get_guild_commands`` or ``HTTPClient.get_global_commands`` to deploy with. If None,
the payload will be retrieved from Discord.
guild_id: Optional[:class:`int`]
Guild ID to deploy application commands to. If ``None``, global commands are deployed to.
associate_known: :class:`bool`
If True, commands on Discord that pass a signature check and a deep check will be associated with locally
added ApplicationCommand objects.
delete_unknown: :class:`bool`
If ``True``, commands on Discord that fail a signature check will be removed. If ``update_known`` is False,
commands that pass the signature check but fail the deep check will also be removed.
update_known: :class:`bool`
If ``True``, commands on Discord that pass a signature check but fail the deep check will be updated.
"""
if not associate_known and not delete_unknown and not update_known:
# If everything is disabled, there is no point in doing anything.
return
if self.application_id is None:
raise NotImplementedError("Could not get the current application id")
if not data:
if guild_id:
# we do not care about typeddict specificity here
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
for raw_response in data:
payload_type = raw_response["type"] if "type" in raw_response else 1
fixed_guild_id = raw_response.get("guild_id", None)
response_signature = {
"type": int(payload_type),
"qualified_name": raw_response["name"],
"guild_id": None if not fixed_guild_id else int(fixed_guild_id),
}
app_cmd = self.get_application_command_from_signature(**response_signature)
if app_cmd:
if not isinstance(app_cmd, BaseApplicationCommand):
raise ValueError(
(
f".get_application_command_from_signature with kwargs: {response_signature} "
f"returned {type(app_cmd)} but BaseApplicationCommand was expected."
)
)
if app_cmd.is_payload_valid(raw_response, guild_id):
if associate_known:
_log.debug(
"nextcord.ConnectionState: Command with signature %s associated with added command.",
response_signature,
)
app_cmd.parse_discord_response(self, raw_response)
self.add_application_command(app_cmd, use_rollout=True)
elif update_known:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, updating.",
response_signature,
)
await self.register_application_command(app_cmd, guild_id)
elif delete_unknown:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, removing.",
response_signature,
)
# TODO: Re-examine how worthwhile this is.
await self.delete_application_command(app_cmd, guild_id)
elif delete_unknown:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, removing.",
response_signature,
)
if guild_id:
await self.http.delete_guild_command(
self.application_id, guild_id, raw_response["id"]
)
else:
await self.http.delete_global_command(self.application_id, raw_response["id"])
async def deploy_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
*,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
) -> None:
warnings.warn(
".deploy_application_commands is deprecated, use .discover_application_commands instead.",
stacklevel=2,
category=FutureWarning,
)
await self.discover_application_commands(
data=data,
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
async def associate_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".associate_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=True,
delete_unknown=False,
update_known=False,
)
async def delete_unknown_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".delete_unknown_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=False,
delete_unknown=True,
update_known=False,
)
async def update_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".update_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=False,
delete_unknown=False,
update_known=True,
)
async def register_new_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
"""|coro|
Registers locally added application commands that don't match a signature that Discord has registered for
either global commands or a specific guild.
Parameters
----------
data: Optional[List[:class:`dict`]]
Data to use when comparing local application commands to what Discord has. Should be a list of application
command data from Discord. If left as ``None``, it will be fetched if needed. Defaults to ``None``
guild_id: Optional[:class:`int`]
ID of the guild to sync application commands with. If set to ``None``, global commands will be synced instead.
Defaults to ``None``.
"""
if not data:
if self.application_id is None:
raise TypeError("Could not get the current application id")
if guild_id:
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
data_signatures = [
(
raw_response["name"],
int(raw_response["type"] if "type" in raw_response else 1),
int(temp) if (temp := raw_response.get("guild_id", None)) else temp,
)
for raw_response in data
]
# add_application_command can change the size of the dictionary, and apparently .items() doesn't prevent that
# "RuntimeError: dictionary changed size during iteration" from happening. So a copy is made for just this.
for signature, app_cmd in self._application_command_signatures.copy().items():
if (
signature not in data_signatures and signature[2] == guild_id
): # index 2 of the tuple is the guild ID.
await self.register_application_command(app_cmd, guild_id)
async def register_application_command(
self, command: BaseApplicationCommand, guild_id: Optional[int] = None
) -> None:
"""|coro|
Registers the given application command either for a specific guild or globally and adds the command to the bot.
Parameters
----------
command: :class:`BaseApplicationCommand`
Application command to register.
guild_id: Optional[:class:`int`]
ID of the guild to register the application commands to. If set to ``None``, the commands will be registered
as global commands instead. Defaults to ``None``.
"""
payload: EditApplicationCommand = command.get_payload(guild_id) # type: ignore
_log.info(
"nextcord.ConnectionState: Registering command with signature %s",
command.get_signature(guild_id),
)
if self.application_id is None:
raise TypeError("Could not get the current application's id")
try:
if guild_id:
raw_response = await self.http.upsert_guild_command(
self.application_id, guild_id, payload
)
else:
raw_response = await self.http.upsert_global_command(self.application_id, payload)
except Exception as e:
_log.error("Error registering command %s: %s", command.error_name, e)
raise e
command.parse_discord_response(self, raw_response)
self.add_application_command(command, pre_remove=False)
async def delete_application_command(
self, command: BaseApplicationCommand, guild_id: Optional[int] = None
) -> None:
"""|coro|
Deletes the given application from Discord for the given guild ID or globally, then removes the signature and
command ID from the cache if possible.
Parameters
----------
command: :class:`ApplicationCommand`
Application command to delete.
guild_id: Optional[:class:`int`]
Guild ID to delete the application commands from. If ``None``, the command is deleted from global.
"""
if self.application_id is None:
raise NotImplementedError("Could not get the current application id")
try:
if guild_id:
await self.http.delete_guild_command(
self.application_id, guild_id, command.command_ids[guild_id]
)
else:
await self.http.delete_global_command(
self.application_id, command.command_ids[guild_id]
)
self._application_command_ids.pop(command.command_ids[guild_id], None)
self._application_command_signatures.pop(command.get_signature(guild_id), None)
except KeyError as e:
if guild_id:
_log.error(
"Could not globally unregister command %s "
"as it is not registered in the provided guild.",
command.error_name,
)
raise KeyError(
"This command cannot be globally unregistered, "
"as it is not registered in the provided guild."
) from e
_log.error(
"Could not globally unregister command %s as it is not a global command.",
command.error_name,
)
raise KeyError(
"This command cannot be globally unregistered, as it is not a global command."
) from e
except Exception as e:
_log.error("Error unregistering command %s: %s", command.error_name, e)
raise e
# async def register_bulk_application_commands(self) -> None:
# # TODO: Using Bulk upsert seems to delete all commands
# # It might be good to keep this around as a reminder for future work. Bulk upsert seem to delete everything
# # that isn't part of that bulk upsert, for both global and guild commands. While useful, this will
# # update/overwrite existing commands, which may (needs testing) wipe out all permissions associated with those
# # commands. Look for an opportunity to use bulk upsert.
# raise NotImplementedError
async def chunker(
self,
guild_id: int,
query: str = "",
limit: int = 0,
presences: bool = False,
*,
nonce: Optional[str] = None,
) -> None:
ws = self._get_websocket(guild_id) # This is ignored upstream
await ws.request_chunks(
guild_id, query=query, limit=limit, presences=presences, nonce=nonce
)
async def query_members(
self,
guild: Guild,
query: Optional[str],
limit: int,
user_ids: Optional[List[int]],
cache: bool,
presences: bool,
) -> List[Member]:
guild_id = guild.id
ws = self._get_websocket(guild_id)
if ws is None: # pyright: ignore[reportUnnecessaryComparison]
raise RuntimeError("Somehow do not have a websocket for this guild_id")
request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache)
self._chunk_requests[request.nonce] = request
try:
# start the query operation
await ws.request_chunks(
guild_id,
query=query,
limit=limit,
user_ids=user_ids,
presences=presences,
nonce=request.nonce,
)
return await asyncio.wait_for(request.wait(), timeout=30.0)
except asyncio.TimeoutError:
_log.warning(
"Timed out waiting for chunks with query %r and limit %d for guild_id %d",
query,
limit,
guild_id,
)
raise
async def _delay_ready(self) -> None:
try:
states = []
while True:
# this snippet of code is basically waiting N seconds
# until the last GUILD_CREATE was sent
try:
guild = await asyncio.wait_for(
self._ready_state.get(), timeout=self.guild_ready_timeout
)
except asyncio.TimeoutError:
break
else:
if self._guild_needs_chunking(guild):
future = await self.chunk_guild(guild, wait=False)
states.append((guild, future))
elif guild.unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
for guild, future in states:
try:
await asyncio.wait_for(future, timeout=5.0)
except asyncio.TimeoutError:
_log.warning(
"Shard ID %s timed out waiting for chunks for guild_id %s.",
guild.shard_id,
guild.id,
)
if guild.unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
# remove the state
# AttributeError: already been deleted somehow
with contextlib.suppress(AttributeError):
del self._ready_state
except asyncio.CancelledError:
pass
else:
# dispatch the event
self.call_handlers("ready")
self.dispatch("ready")
finally:
self._ready_task = None
def parse_ready(self, data) -> None:
if self._ready_task is not None:
self._ready_task.cancel()
self._ready_state = asyncio.Queue()
self.clear(views=False)
self.user = ClientUser(state=self, data=data["user"])
self.store_user(data["user"])
if self.application_id is None:
try:
application = data["application"]
except KeyError:
pass
else:
self.application_id = utils.get_as_snowflake(application, "id")
# flags will always be present here
self.application_flags = ApplicationFlags._from_value(application["flags"])
for guild_data in data["guilds"]:
self._add_guild_from_data(guild_data)
self.dispatch("connect")
self._ready_task = asyncio.create_task(self._delay_ready())
def parse_resumed(self, data) -> None:
self.dispatch("resumed")
def parse_message_create(self, data) -> None:
channel, _ = self._get_guild_channel(data)
# channel would be the correct type here
message = Message(channel=channel, data=data, state=self) # type: ignore
self.dispatch("message", message)
if self._messages is not None:
self._messages.append(message)
# we ensure that the channel is either a TextChannel, ForumChannel, Thread or VoiceChannel
if channel and channel.__class__ in (TextChannel, ForumChannel, Thread, VoiceChannel):
channel.last_message_id = message.id # type: ignore
def parse_message_delete(self, data) -> None:
raw = RawMessageDeleteEvent(data)
found = self._get_message(raw.message_id)
raw.cached_message = found
self.dispatch("raw_message_delete", raw)
if self._messages is not None and found is not None:
self.dispatch("message_delete", found)
self._messages.remove(found)
def parse_message_delete_bulk(self, data) -> None:
raw = RawBulkMessageDeleteEvent(data)
if self._messages:
found_messages = [
message for message in self._messages if message.id in raw.message_ids
]
else:
found_messages = []
raw.cached_messages = found_messages
self.dispatch("raw_bulk_message_delete", raw)
if found_messages:
self.dispatch("bulk_message_delete", found_messages)
for msg in found_messages:
# self._messages won't be None here
self._messages.remove(msg) # type: ignore
def parse_message_update(self, data) -> None:
raw = RawMessageUpdateEvent(data)
message = self._get_message(raw.message_id)
if message is not None:
older_message = copy.copy(message)
raw.cached_message = older_message
self.dispatch("raw_message_edit", raw)
message._update(data)
# Coerce the `after` parameter to take the new updated Member
# ref: #5999
older_message.author = message.author
self.dispatch("message_edit", older_message, message)
else:
self.dispatch("raw_message_edit", raw)
if "components" in data and self._view_store.is_message_tracked(raw.message_id):
self._view_store.update_from_message(raw.message_id, data["components"])
def parse_message_reaction_add(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(
self, id=emoji_id, animated=emoji.get("animated", False), name=emoji["name"]
)
raw = RawReactionActionEvent(data, emoji, "REACTION_ADD")
member_data = data.get("member")
if member_data:
guild = self._get_guild(raw.guild_id)
if guild is not None:
raw.member = Member(data=member_data, guild=guild, state=self)
else:
raw.member = None
else:
raw.member = None
self.dispatch("raw_reaction_add", raw)
# rich interface here
message = self._get_message(raw.message_id)
if message is not None:
emoji = self._upgrade_partial_emoji(emoji)
reaction = message._add_reaction(data, emoji, raw.user_id)
user = raw.member or self._get_reaction_user(message.channel, raw.user_id)
if user:
self.dispatch("reaction_add", reaction, user)
def parse_message_reaction_remove_all(self, data) -> None:
raw = RawReactionClearEvent(data)
self.dispatch("raw_reaction_clear", raw)
message = self._get_message(raw.message_id)
if message is not None:
old_reactions = message.reactions.copy()
message.reactions.clear()
self.dispatch("reaction_clear", message, old_reactions)
def parse_message_reaction_remove(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji["name"])
raw = RawReactionActionEvent(data, emoji, "REACTION_REMOVE")
self.dispatch("raw_reaction_remove", raw)
message = self._get_message(raw.message_id)
if message is not None:
emoji = self._upgrade_partial_emoji(emoji)
try:
reaction = message._remove_reaction(data, emoji, raw.user_id)
except (AttributeError, ValueError): # eventual consistency lol
pass
else:
user = self._get_reaction_user(message.channel, raw.user_id)
if user:
self.dispatch("reaction_remove", reaction, user)
def parse_message_reaction_remove_emoji(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji["name"])
raw = RawReactionClearEmojiEvent(data, emoji)
self.dispatch("raw_reaction_clear_emoji", raw)
message = self._get_message(raw.message_id)
if message is not None:
try:
reaction = message._clear_emoji(emoji)
except (AttributeError, ValueError): # eventual consistency lol
pass
else:
if reaction:
self.dispatch("reaction_clear_emoji", reaction)
def parse_interaction_create(self, data) -> None:
interaction = self._get_client().get_interaction(data=data)
if data["type"] == 3: # interaction component
custom_id = interaction.data["custom_id"] # type: ignore
component_type = interaction.data["component_type"] # type: ignore
self._view_store.dispatch(component_type, custom_id, interaction)
if data["type"] == 5: # modal submit
custom_id = interaction.data["custom_id"] # type: ignore
# key exists if type is 5 etc
self._modal_store.dispatch(custom_id, interaction)
self.dispatch("interaction", interaction)
def parse_presence_update(self, data) -> None:
guild_id = utils.get_as_snowflake(data, "guild_id")
# guild_id won't be None here
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("PRESENCE_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id)
return
user = data["user"]
member_id = int(user["id"])
member = guild.get_member(member_id)
if member is None:
_log.debug(
"PRESENCE_UPDATE referencing an unknown member ID: %s. Discarding", member_id
)
return
old_member = Member._copy(member)
user_update = member._presence_update(data=data, user=user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
self.dispatch("presence_update", old_member, member)
def parse_user_update(self, data) -> None:
# self.user is *always* cached when this is called
user: ClientUser = self.user # type: ignore
user._update(data)
ref = self._users.get(user.id)
if ref:
ref._update(data)
def parse_invite_create(self, data) -> None:
invite = Invite.from_gateway(state=self, data=data)
self.dispatch("invite_create", invite)
def parse_invite_delete(self, data) -> None:
invite = Invite.from_gateway(state=self, data=data)
self.dispatch("invite_delete", invite)
def parse_channel_delete(self, data) -> None:
guild = self._get_guild(utils.get_as_snowflake(data, "guild_id"))
channel_id = int(data["id"])
if guild is not None:
channel = guild.get_channel(channel_id)
if channel is not None:
guild._remove_channel(channel)
self.dispatch("guild_channel_delete", channel)
def parse_channel_update(self, data) -> None:
channel_type = try_enum(ChannelType, data.get("type"))
channel_id = int(data["id"])
if channel_type is ChannelType.group:
channel = self._get_private_channel(channel_id)
old_channel = copy.copy(channel)
# the channel is a GroupChannel
channel._update_group(data) # type: ignore
self.dispatch("private_channel_update", old_channel, channel)
return
guild_id = utils.get_as_snowflake(data, "guild_id")
guild = self._get_guild(guild_id)
if guild is not None:
channel = guild.get_channel(channel_id)
if channel is not None:
old_channel = copy.copy(channel)
channel._update(guild, data)
self.dispatch("guild_channel_update", old_channel, channel)
else:
_log.debug(
"CHANNEL_UPDATE referencing an unknown channel ID: %s. Discarding.", channel_id
)
else:
_log.debug("CHANNEL_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id)
def parse_channel_create(self, data) -> None:
factory, _ = _channel_factory(data["type"])
if factory is None:
_log.debug(
"CHANNEL_CREATE referencing an unknown channel type %s. Discarding.", data["type"]
)
return
guild_id = utils.get_as_snowflake(data, "guild_id")
guild = self._get_guild(guild_id)
if guild is not None:
# the factory can't be a DMChannel or GroupChannel here
channel = factory(guild=guild, state=self, data=data) # type: ignore
guild._add_channel(channel) # type: ignore
self.dispatch("guild_channel_create", channel)
else:
_log.debug("CHANNEL_CREATE referencing an unknown guild ID: %s. Discarding.", guild_id)
return
def parse_channel_pins_update(self, data) -> None:
channel_id = int(data["channel_id"])
try:
guild = self._get_guild(int(data["guild_id"]))
except KeyError:
guild = None
channel = self._get_private_channel(channel_id)
else:
channel = guild and guild._resolve_channel(channel_id)
if channel is None:
_log.debug(
"CHANNEL_PINS_UPDATE referencing an unknown channel ID: %s. Discarding.", channel_id
)
return
last_pin = (
utils.parse_time(data["last_pin_timestamp"]) if data["last_pin_timestamp"] else None
)
if guild is None:
self.dispatch("private_channel_pins_update", channel, last_pin)
else:
self.dispatch("guild_channel_pins_update", channel, last_pin)
def parse_thread_create(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_CREATE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread = Thread(guild=guild, state=guild._state, data=data)
has_thread = guild.get_thread(thread.id)
guild._add_thread(thread)
if not has_thread:
# `newly_created` is documented outside of a thread's fields:
# https://discord.dev/topics/gateway-events#thread-create
if data.get("newly_created", False):
if isinstance(thread.parent, ForumChannel):
thread.parent.last_message_id = thread.id
self.dispatch("thread_create", thread)
# Avoid an unnecessary breaking change right now by dispatching `thread_join` for
# threads that were already created.
self.dispatch("thread_join", thread)
def parse_thread_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread_id = int(data["id"])
thread = guild.get_thread(thread_id)
if thread is not None:
old = copy.copy(thread)
thread._update(data)
self.dispatch("thread_update", old, thread)
else:
thread = Thread(guild=guild, state=guild._state, data=data)
guild._add_thread(thread)
self.dispatch("thread_join", thread)
def parse_thread_delete(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_DELETE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread_id = int(data["id"])
thread = guild.get_thread(thread_id)
if thread is not None:
guild._remove_thread(thread)
self.dispatch("thread_delete", thread)
def parse_thread_list_sync(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_LIST_SYNC referencing an unknown guild ID: %s. Discarding", guild_id)
return
try:
channel_ids = set(data["channel_ids"])
except KeyError:
# If not provided, then the entire guild is being synced
# So all previous thread data should be overwritten
previous_threads = guild._threads.copy()
guild._clear_threads()
else:
previous_threads = guild._filter_threads(channel_ids)
threads = {d["id"]: guild._store_thread(d) for d in data.get("threads", [])}
for member in data.get("members", []):
try:
# note: member['id'] is the thread_id
thread = threads[member["id"]]
except KeyError:
continue
else:
thread._add_member(ThreadMember(thread, member))
for thread in threads.values():
old = previous_threads.pop(thread.id, None)
if old is None:
self.dispatch("thread_join", thread)
for thread in previous_threads.values():
self.dispatch("thread_remove", thread)
def parse_thread_member_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug(
"THREAD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id
)
return
thread_id = int(data["id"])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
_log.debug(
"THREAD_MEMBER_UPDATE referencing an unknown thread ID: %s. Discarding", thread_id
)
return
member = ThreadMember(thread, data)
thread.me = member
def parse_thread_members_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug(
"THREAD_MEMBERS_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id
)
return
thread_id = int(data["id"])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
_log.debug(
"THREAD_MEMBERS_UPDATE referencing an unknown thread ID: %s. Discarding", thread_id
)
return
added_members = [ThreadMember(thread, d) for d in data.get("added_members", [])]
removed_member_ids = [int(x) for x in data.get("removed_member_ids", [])]
self_id = self.self_id
for member in added_members:
if member.id != self_id:
thread._add_member(member)
self.dispatch("thread_member_join", member)
else:
thread.me = member
self.dispatch("thread_join", thread)
for member_id in removed_member_ids:
if member_id != self_id:
member = thread._pop_member(member_id)
if member is not None:
self.dispatch("thread_member_remove", member)
else:
self.dispatch("thread_remove", thread)
def parse_guild_member_add(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_MEMBER_ADD referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
member = Member(guild=guild, data=data, state=self)
if self.member_cache_flags.joined:
guild._add_member(member)
with contextlib.suppress(AttributeError):
guild._member_count += 1
self.dispatch("member_join", member)
def parse_guild_member_remove(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
with contextlib.suppress(AttributeError):
guild._member_count -= 1
user_id = int(data["user"]["id"])
member = guild.get_member(user_id)
if member is not None:
guild._remove_member(member)
self.dispatch("member_remove", member)
else:
_log.debug(
(
"GUILD_MEMBER_REMOVE referencing an unknown guild ID: %s."
"Falling back to raw data."
),
data["guild_id"],
)
raw = RawMemberRemoveEvent(data=data, state=self)
self.dispatch("raw_member_remove", raw)
def parse_guild_member_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
user = data["user"]
user_id = int(user["id"])
if guild is None:
_log.debug(
"GUILD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
member = guild.get_member(user_id)
if member is not None:
old_member = Member._copy(member)
member._update(data)
user_update = member._update_inner_user(user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
self.dispatch("member_update", old_member, member)
else:
if self.member_cache_flags.joined:
member = Member(data=data, guild=guild, state=self)
# Force an update on the inner user if necessary
user_update = member._update_inner_user(user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
guild._add_member(member)
_log.debug(
"GUILD_MEMBER_UPDATE referencing an unknown member ID: %s. Discarding.", user_id
)
def parse_guild_emojis_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_EMOJIS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
before_emojis = guild.emojis
for emoji in before_emojis:
self._emojis.pop(emoji.id, None)
guild.emojis = tuple([self.store_emoji(guild, d) for d in data["emojis"]])
self.dispatch("guild_emojis_update", guild, before_emojis, guild.emojis)
def parse_guild_stickers_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_STICKERS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
before_stickers = guild.stickers
for emoji in before_stickers:
self._stickers.pop(emoji.id, None)
guild.stickers = tuple([self.store_sticker(guild, d) for d in data["stickers"]])
self.dispatch("guild_stickers_update", guild, before_stickers, guild.stickers)
def _get_create_guild(self, data):
if data.get("unavailable") is False:
# GUILD_CREATE with unavailable in the response
# usually means that the guild has become available
# and is therefore in the cache
guild = self._get_guild(int(data["id"]))
if guild is not None:
guild.unavailable = False
guild._from_data(data)
return guild
return self._add_guild_from_data(data)
def is_guild_evicted(self, guild) -> bool:
return guild.id not in self._guilds
async def chunk_guild(self, guild, *, wait: bool = True, cache=None):
if cache is None:
cache = self.member_cache_flags.joined
request = self._chunk_requests.get(guild.id)
if request is None:
self._chunk_requests[guild.id] = request = ChunkRequest(
guild.id, self.loop, self._get_guild, cache=cache
)
await self.chunker(guild.id, nonce=request.nonce)
if wait:
return await request.wait()
return request.get_future()
async def _chunk_and_dispatch(self, guild, unavailable) -> None:
try:
await asyncio.wait_for(self.chunk_guild(guild), timeout=60.0)
except asyncio.TimeoutError:
_log.info("Somehow timed out waiting for chunks.")
if unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
def parse_guild_create(self, data) -> None:
unavailable = data.get("unavailable")
if unavailable is True:
# joined a guild with unavailable == True so..
return
guild = self._get_create_guild(data)
try:
# Notify the on_ready state, if any, that this guild is complete.
self._ready_state.put_nowait(guild)
except AttributeError:
pass
else:
# If we're waiting for the event, put the rest on hold
return
# check if it requires chunking
if self._guild_needs_chunking(guild):
task = asyncio.create_task(self._chunk_and_dispatch(guild, unavailable))
self._chunk_tasks[guild.id] = task
task.add_done_callback(lambda _t: self._chunk_tasks.pop(guild.id, None))
return
# Dispatch available if newly available
if unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
def parse_guild_update(self, data) -> None:
guild = self._get_guild(int(data["id"]))
if guild is not None:
old_guild = copy.copy(guild)
guild._from_data(data)
self.dispatch("guild_update", old_guild, guild)
else:
_log.debug("GUILD_UPDATE referencing an unknown guild ID: %s. Discarding.", data["id"])
def parse_guild_delete(self, data) -> None:
guild = self._get_guild(int(data["id"]))
if guild is None:
_log.debug("GUILD_DELETE referencing an unknown guild ID: %s. Discarding.", data["id"])
return
if data.get("unavailable", False):
# GUILD_DELETE with unavailable being True means that the
# guild that was available is now currently unavailable
guild.unavailable = True
self.dispatch("guild_unavailable", guild)
return
# do a cleanup of the messages cache
if self._messages is not None:
self._messages: Optional[Deque[Message]] = deque(
(msg for msg in self._messages if msg.guild != guild), maxlen=self.max_messages
)
self._remove_guild(guild)
self.dispatch("guild_remove", guild)
def parse_guild_ban_add(self, data) -> None:
# we make the assumption that GUILD_BAN_ADD is done
# before GUILD_MEMBER_REMOVE is called
# hence we don't remove it from cache or do anything
# strange with it, the main purpose of this event
# is mainly to dispatch to another event worth listening to for logging
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
try:
user = User(data=data["user"], state=self)
except KeyError:
pass
else:
member = guild.get_member(user.id) or user
self.dispatch("member_ban", guild, member)
def parse_guild_ban_remove(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None and "user" in data:
user = self.store_user(data["user"])
self.dispatch("member_unban", guild, user)
def parse_guild_role_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_ROLE_CREATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
role_data = data["role"]
role = Role(guild=guild, data=role_data, state=self)
guild._add_role(role)
self.dispatch("guild_role_create", role)
def parse_guild_role_delete(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
role_id = int(data["role_id"])
try:
role = guild._remove_role(role_id)
except KeyError:
return
else:
self.dispatch("guild_role_delete", role)
else:
_log.debug(
"GUILD_ROLE_DELETE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_role_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
role_data = data["role"]
role_id = int(role_data["id"])
role = guild.get_role(role_id)
if role is not None:
old_role = copy.copy(role)
role._update(role_data)
self.dispatch("guild_role_update", old_role, role)
else:
_log.debug(
"GUILD_ROLE_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_members_chunk(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
presences = data.get("presences", [])
# the guild won't be None here
members = [Member(guild=guild, data=member, state=self) for member in data.get("members", [])] # type: ignore
_log.debug("Processed a chunk for %s members in guild ID %s.", len(members), guild_id)
if presences:
member_dict = {str(member.id): member for member in members}
for presence in presences:
user = presence["user"]
member_id = user["id"]
member = member_dict.get(member_id)
if member is not None:
member._presence_update(presence, user)
complete = data.get("chunk_index", 0) + 1 == data.get("chunk_count")
self.process_chunk_requests(guild_id, data.get("nonce"), members, complete)
def parse_guild_integrations_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
self.dispatch("guild_integrations_update", guild)
else:
_log.debug(
"GUILD_INTEGRATIONS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_integration_create(self, data) -> None:
guild_id = int(data.pop("guild_id"))
guild = self._get_guild(guild_id)
if guild is not None:
cls, _ = _integration_factory(data["type"])
integration = cls(data=data, guild=guild)
self.dispatch("integration_create", integration)
else:
_log.debug(
"INTEGRATION_CREATE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_integration_update(self, data) -> None:
guild_id = int(data.pop("guild_id"))
guild = self._get_guild(guild_id)
if guild is not None:
cls, _ = _integration_factory(data["type"])
integration = cls(data=data, guild=guild)
self.dispatch("integration_update", integration)
else:
_log.debug(
"INTEGRATION_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_integration_delete(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is not None:
raw = RawIntegrationDeleteEvent(data)
self.dispatch("raw_integration_delete", raw)
else:
_log.debug(
"INTEGRATION_DELETE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_webhooks_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"WEBHOOKS_UPDATE referencing an unknown guild ID: %s. Discarding", data["guild_id"]
)
return
channel = guild.get_channel(int(data["channel_id"]))
if channel is not None:
self.dispatch("webhooks_update", channel)
else:
_log.debug(
"WEBHOOKS_UPDATE referencing an unknown channel ID: %s. Discarding.",
data["channel_id"],
)
def parse_stage_instance_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
stage_instance = StageInstance(guild=guild, state=self, data=data)
guild._stage_instances[stage_instance.id] = stage_instance
self.dispatch("stage_instance_create", stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_CREATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_stage_instance_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
stage_instance = guild._stage_instances.get(int(data["id"]))
if stage_instance is not None:
old_stage_instance = copy.copy(stage_instance)
stage_instance._update(data)
self.dispatch("stage_instance_update", old_stage_instance, stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_UPDATE referencing unknown stage instance ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"STAGE_INSTANCE_UPDATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_stage_instance_delete(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
try:
stage_instance = guild._stage_instances.pop(int(data["id"]))
except KeyError:
pass
else:
self.dispatch("stage_instance_delete", stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_DELETE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_voice_state_update(self, data) -> None:
guild = self._get_guild(utils.get_as_snowflake(data, "guild_id"))
channel_id = utils.get_as_snowflake(data, "channel_id")
flags = self.member_cache_flags
# self.user is *always* cached when this is called
self_id = self.user.id # type: ignore
if guild is not None:
if int(data["user_id"]) == self_id:
voice = self._get_voice_client(guild.id)
if voice is not None:
coro = voice.on_voice_state_update(data)
task = asyncio.create_task(
logging_coroutine(coro, info="Voice Protocol voice state update handler")
)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
member, before, after = guild._update_voice_state(data, channel_id) # type: ignore
after = copy.copy(after)
if member is not None:
if flags.voice:
if channel_id is None and flags._voice_only and member.id != self_id:
# Only remove from cache if we only have the voice flag enabled
# Member doesn't meet the Snowflake protocol currently
guild._remove_member(member)
elif channel_id is not None:
guild._add_member(member)
self.dispatch("voice_state_update", member, before, after)
else:
_log.debug(
"VOICE_STATE_UPDATE referencing an unknown member ID: %s. Discarding.",
data["user_id"],
)
def parse_voice_server_update(self, data) -> None:
try:
key_id = int(data["guild_id"])
except KeyError:
key_id = int(data["channel_id"])
vc = self._get_voice_client(key_id)
if vc is not None:
coro = vc.on_voice_server_update(data)
task = asyncio.create_task(
logging_coroutine(coro, info="Voice Protocol voice server update handler")
)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
def parse_typing_start(self, data) -> None:
raw = RawTypingEvent(data)
member_data = data.get("member")
if member_data:
guild = self._get_guild(raw.guild_id)
if guild is not None:
raw.member = Member(data=member_data, guild=guild, state=self)
else:
raw.member = None
else:
raw.member = None
self.dispatch("raw_typing", raw)
channel, guild = self._get_guild_channel(data)
if channel is not None: # pyright: ignore[reportUnnecessaryComparison]
user = raw.member or self._get_typing_user(channel, raw.user_id) # type: ignore
# will be messageable channel if we get here
if user is not None:
self.dispatch("typing", channel, user, raw.when)
def _get_typing_user(
self, channel: Optional[MessageableChannel], user_id: int
) -> Optional[Union[User, Member]]:
if isinstance(channel, DMChannel):
return channel.recipient or self.get_user(user_id)
if isinstance(channel, (Thread, TextChannel)):
return channel.guild.get_member(user_id)
if isinstance(channel, GroupChannel):
return utils.find(lambda x: x.id == user_id, channel.recipients)
return self.get_user(user_id)
def _get_reaction_user(
self, channel: MessageableChannel, user_id: int
) -> Optional[Union[User, Member]]:
if isinstance(channel, TextChannel):
return channel.guild.get_member(user_id)
return self.get_user(user_id)
def get_reaction_emoji(self, data) -> Union[Emoji, PartialEmoji]:
emoji_id = utils.get_as_snowflake(data, "id")
if not emoji_id:
return data["name"]
try:
return self._emojis[emoji_id]
except KeyError:
return PartialEmoji.with_state(
self, animated=data.get("animated", False), id=emoji_id, name=data["name"]
)
def _upgrade_partial_emoji(self, emoji: PartialEmoji) -> Union[Emoji, PartialEmoji, str]:
emoji_id = emoji.id
if not emoji_id:
return emoji.name
try:
return self._emojis[emoji_id]
except KeyError:
return emoji
def get_channel(self, id: Optional[int]) -> Optional[Union[Channel, Thread]]:
if id is None:
return None
pm = self._get_private_channel(id)
if pm is not None:
return pm
for guild in self.guilds:
channel = guild._resolve_channel(id)
if channel is not None:
return channel
return None
def get_scheduled_event(self, id: int) -> Optional[ScheduledEvent]:
for guild in self.guilds:
if event := guild.get_scheduled_event(id):
return event
return None
def create_message(
self,
*,
channel: MessageableChannel,
data: MessagePayload,
) -> Message:
return Message(state=self, channel=channel, data=data)
def create_scheduled_event(
self, *, guild: Guild, data: ScheduledEventPayload
) -> ScheduledEvent:
return ScheduledEvent(state=self, guild=guild, data=data)
def parse_guild_scheduled_event_create(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
event = self.create_scheduled_event(guild=guild, data=data)
guild._add_scheduled_event(event)
self.dispatch("guild_scheduled_event_create", event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_CREATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_update(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["id"])):
old = copy.copy(event)
event._update(data)
self.dispatch("guild_scheduled_event_update", old, event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_UPDATE referencing unknown event ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_UPDATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_delete(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["id"])):
guild._remove_scheduled_event(event.id)
self.dispatch("guild_scheduled_event_delete", event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_DELETE referencing unknown event ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_DELETE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_user_add(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["guild_scheduled_event_id"])):
u = ScheduledEventUser.from_id(
event=event, user_id=int(data["user_id"]), state=self
)
event._add_user(u)
self.dispatch("guild_scheduled_event_user_add", event, u)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_ADD referencing unknown"
" event ID: %s. Discarding.",
data["user_id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_ADD referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_user_remove(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["guild_scheduled_event_id"])):
event._remove_user(int(data["user_id"]))
self.dispatch(
"guild_scheduled_event_user_remove",
event,
ScheduledEventUser.from_id(
event=event, user_id=int(data["user_id"]), state=self
),
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_REMOVE referencing unknown"
" event ID: %s. Discarding.",
data["user_id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_REMOVE referencing unknown"
" guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_auto_moderation_rule_create(self, data) -> None:
self.dispatch(
"auto_moderation_rule_create",
AutoModerationRule(data=data, state=self),
)
def parse_auto_moderation_rule_update(self, data) -> None:
self.dispatch("auto_moderation_rule_update", AutoModerationRule(data=data, state=self))
def parse_auto_moderation_rule_delete(self, data) -> None:
self.dispatch("auto_moderation_rule_delete", AutoModerationRule(data=data, state=self))
def parse_auto_moderation_action_execution(self, data) -> None:
self.dispatch(
"auto_moderation_action_execution", AutoModerationActionExecution(data=data, state=self)
)
def parse_guild_audit_log_entry_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
user_id = None if data.get("user_id") is None else int(data["user_id"])
user = self.get_user(user_id)
users = {} if user_id is None or user is None else {user_id: user}
if guild is not None:
entry = AuditLogEntry(auto_moderation_rules={}, users=users, data=data, guild=guild)
self.dispatch("guild_audit_log_entry_create", entry)
else:
_log.debug(
"guild_audit_log_entry_create wasn't dispatched because the guild (%r) and/or user (%r) are None!",
guild,
user,
)
The provided code snippet includes necessary dependencies for implementing the `get_roles_from_interaction` function. Write a Python function `def get_roles_from_interaction(state: ConnectionState, interaction: Interaction) -> List[Role]` to solve the following problem:
Tries to get a list of resolved :class:`Role` objects from the interaction .data Parameters ---------- state: :class:`ConnectionState` State object to construct roles with. interaction: :class:`Interaction` Interaction object to attempt to get resolved roles from. Returns ------- List[:class:`Role`] A list of resolved roles.
Here is the function:
def get_roles_from_interaction(state: ConnectionState, interaction: Interaction) -> List[Role]:
"""Tries to get a list of resolved :class:`Role` objects from the interaction .data
Parameters
----------
state: :class:`ConnectionState`
State object to construct roles with.
interaction: :class:`Interaction`
Interaction object to attempt to get resolved roles from.
Returns
-------
List[:class:`Role`]
A list of resolved roles.
"""
data = interaction.data
ret = []
if data is None:
raise ValueError("Discord did not provide us with interaction data")
data = cast(ApplicationCommandInteractionData, data)
if "resolved" in data and "roles" in data["resolved"]:
role_payloads = data["resolved"]["roles"]
for role_id, role_payload in role_payloads.items():
# if True: # Use this for testing payload -> Role
if interaction.guild is None:
raise TypeError("Interaction.guild is None when resolving a Role")
if not (role := interaction.guild.get_role(int(role_id))):
role = Role(guild=interaction.guild, state=state, data=role_payload)
ret.append(role)
return ret | Tries to get a list of resolved :class:`Role` objects from the interaction .data Parameters ---------- state: :class:`ConnectionState` State object to construct roles with. interaction: :class:`Interaction` Interaction object to attempt to get resolved roles from. Returns ------- List[:class:`Role`] A list of resolved roles. |
160,992 | from __future__ import annotations
import asyncio
import contextlib
import logging
import sys
import warnings
from inspect import Parameter, signature
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Coroutine,
Dict,
Iterable,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
import typing_extensions
from typing_extensions import Annotated
from .abc import GuildChannel
from .channel import (
CategoryChannel,
DMChannel,
ForumChannel,
GroupChannel,
StageChannel,
TextChannel,
VoiceChannel,
)
from .enums import ApplicationCommandOptionType, ApplicationCommandType, ChannelType, Locale
from .errors import (
ApplicationCheckFailure,
ApplicationCommandOptionMissing,
ApplicationError,
ApplicationInvokeError,
)
from .guild import Guild
from .interactions import Interaction
from .member import Member
from .message import Attachment, Message
from .object import Object
from .permissions import Permissions
from .role import Role
from .threads import Thread
from .types.interactions import ApplicationCommandInteractionData
from .user import User
from .utils import MISSING, find, maybe_coroutine, parse_docstring
def unpack_annotated(given_annotation: Any, resolve_list: Optional[list[type]] = None) -> Any:
"""Takes an annotation. If the origin is Annotated, it will attempt to resolve it using the given list of accepted
types, going from the last type and working up to the first. If no matches to the given list is found, the last
type specified in the Annotated typehint will be returned.
If the origin is not Annotated, the typehint will be returned as-is.
Parameters
----------
given_annotation
Annotation to attempt to resolve.
resolve_list
List of types the annotation can resolve to.
Returns
-------
:class:`type`
Resolved annotation.
"""
if resolve_list is None:
resolve_list = []
# TODO: Once Python 3.10 is standard, use this.
# origin = typing.get_origin(given_annotation) # noqa: ERA001
origin = typing_extensions.get_origin(given_annotation)
if origin is Annotated:
located_annotation = MISSING
# TODO: Once Python 3.10 is standard, use this
# arg_list = typing.get_args(given_annotation) # noqa: ERA001
arg_list = typing_extensions.get_args(given_annotation)
for arg in reversed(arg_list[1:]):
if arg in resolve_list or isinstance(arg, type) and issubclass(arg, OptionConverter):
located_annotation = arg
break
if located_annotation is MISSING:
located_annotation = arg_list[-1]
return located_annotation
return given_annotation
The provided code snippet includes necessary dependencies for implementing the `unpack_annotation` function. Write a Python function `def unpack_annotation( given_annotation: Any, annotated_list: Optional[List[type]] = None ) -> Tuple[List[type], list]` to solve the following problem:
Unpacks the given parameter annotation into its components. Parameters ---------- given_annotation: Any Given annotation to unpack. Should be from ``parameter.annotation`` annotated_list: List[:class:`type`] List that the ``Annotated`` annotation should attempt to resolve to, from the 2nd arg to the right. Returns ------- Tuple[List[:class:`type`], :class:`list`] A list of unpacked type annotations, and a list of unpacked literal arguments.
Here is the function:
def unpack_annotation(
given_annotation: Any, annotated_list: Optional[List[type]] = None
) -> Tuple[List[type], list]:
"""Unpacks the given parameter annotation into its components.
Parameters
----------
given_annotation: Any
Given annotation to unpack. Should be from ``parameter.annotation``
annotated_list: List[:class:`type`]
List that the ``Annotated`` annotation should attempt to resolve to, from the 2nd arg to the right.
Returns
-------
Tuple[List[:class:`type`], :class:`list`]
A list of unpacked type annotations,
and a list of unpacked literal arguments.
"""
if annotated_list is None:
annotated_list = []
type_ret = []
literal_ret = []
# TODO: Once Python 3.10 is standard, use this.
# origin = typing.get_origin(given_annotation) # noqa: ERA001
origin = typing_extensions.get_origin(given_annotation)
if origin is None:
# It doesn't have a fancy origin, just a normal type/object.
if isinstance(given_annotation, type):
type_ret.append(given_annotation)
else:
# If it's not a type and the origin is None, it's probably a literal.
literal_ret.append(given_annotation)
elif origin is Annotated:
located_annotation = unpack_annotated(given_annotation, annotated_list)
unpacked_type, unpacked_literal = unpack_annotation(located_annotation, annotated_list)
type_ret.extend(unpacked_type)
literal_ret.extend(unpacked_literal)
elif origin in (Union, UnionType, Optional, Literal):
# Note for someone refactoring this: UnionType (at this time) will be None on Python sub-3.10
# This doesn't matter for now since None is explicitly checked first, but may trip you up when modifying this.
# for anno in typing.get_args(given_annotation): # TODO: Once Python 3.10 is standard, use this.
for anno in typing_extensions.get_args(given_annotation):
unpacked_type, unpacked_literal = unpack_annotation(anno, annotated_list)
type_ret.extend(unpacked_type)
literal_ret.extend(unpacked_literal)
else:
raise ValueError(f"Given Annotation {given_annotation} has an unhandled origin: {origin}")
return type_ret, literal_ret | Unpacks the given parameter annotation into its components. Parameters ---------- given_annotation: Any Given annotation to unpack. Should be from ``parameter.annotation`` annotated_list: List[:class:`type`] List that the ``Annotated`` annotation should attempt to resolve to, from the 2nd arg to the right. Returns ------- Tuple[List[:class:`type`], :class:`list`] A list of unpacked type annotations, and a list of unpacked literal arguments. |
160,993 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import itertools
import sys
from operator import attrgetter
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple, Union
from . import abc, utils
from .activity import ActivityTypes, create_activity
from .asset import Asset
from .colour import Colour
from .enums import Status, try_enum
from .flags import MemberFlags
from .object import Object
from .permissions import Permissions
from .user import BaseUser, User, _UserTag
from .utils import MISSING
class BaseUser(_UserTag):
__slots__ = (
"name",
"id",
"discriminator",
"_avatar",
"_banner",
"_accent_colour",
"bot",
"system",
"_public_flags",
"_state",
"global_name",
)
if TYPE_CHECKING:
name: str
id: int
discriminator: str
bot: bool
system: bool
global_name: Optional[str]
_state: ConnectionState
_avatar: Optional[str]
_banner: Optional[str]
_accent_colour: Optional[str]
_public_flags: int
def __init__(
self, *, state: ConnectionState, data: Union[PartialUserPayload, UserPayload]
) -> None:
self._state = state
self._update(data)
def __repr__(self) -> str:
return (
f"<BaseUser id={self.id} name={self.name!r} global_name={self.global_name!r}"
+ (f" discriminator={self.discriminator!r}" if self.discriminator != "0" else "")
+ f" bot={self.bot} system={self.system}>"
)
def __str__(self) -> str:
return f"{self.name}#{self.discriminator}" if self.discriminator != "0" else self.name
def __eq__(self, other: Any) -> bool:
return isinstance(other, _UserTag) and other.id == self.id
def __ne__(self, other: Any) -> bool:
return not self.__eq__(other)
def __hash__(self) -> int:
return self.id >> 22
def _update(self, data: Union[PartialUserPayload, UserPayload]) -> None:
self.name = data["username"]
self.id = int(data["id"])
self.discriminator = data["discriminator"]
self._avatar = data["avatar"]
self._banner = data.get("banner", None)
self._accent_colour = data.get("accent_color", None)
self._public_flags = data.get("public_flags", 0)
self.bot = data.get("bot", False)
self.system = data.get("system", False)
self.global_name = data.get("global_name", None)
def _copy(cls, user: Self) -> Self:
self = cls.__new__(cls) # bypass __init__
self.name = user.name
self.id = user.id
self.discriminator = user.discriminator
self._avatar = user._avatar
self._banner = user._banner
self._accent_colour = user._accent_colour
self.bot = user.bot
self._state = user._state
self._public_flags = user._public_flags
return self
def _to_minimal_user_json(self) -> Dict[str, Any]:
return {
"username": self.name,
"id": self.id,
"avatar": self._avatar,
"global_name": self.global_name,
"discriminator": self.discriminator, # TODO: possibly remove this?
"bot": self.bot,
}
def public_flags(self) -> PublicUserFlags:
""":class:`PublicUserFlags`: The publicly available flags the user has."""
return PublicUserFlags._from_value(self._public_flags)
def avatar(self) -> Optional[Asset]:
"""Optional[:class:`Asset`]: Returns an :class:`Asset` for the avatar the user has.
If the user does not have a traditional avatar, ``None`` is returned.
If you want the avatar that a user has displayed, consider :attr:`display_avatar`.
"""
if self._avatar is not None:
return Asset._from_avatar(self._state, self.id, self._avatar)
return None
def default_avatar(self) -> Asset:
""":class:`Asset`: Returns the default avatar for a given user.
This is calculated by the user's discriminator.
..versionchanged:: 2.6
Added handling for the new username system for users without a discriminator.
"""
if self.discriminator != "0":
avatar_index = (self.id >> 22) % len(DefaultAvatar)
else:
avatar_index = int(self.discriminator) % 5
return Asset._from_default_avatar(self._state, avatar_index)
def display_avatar(self) -> Asset:
""":class:`Asset`: Returns the user's display avatar.
For regular users this is just their default avatar or uploaded avatar.
.. versionadded:: 2.0
"""
return self.avatar or self.default_avatar
def banner(self) -> Optional[Asset]:
"""Optional[:class:`Asset`]: Returns the user's banner asset, if available.
.. versionadded:: 2.0
.. note::
This information is only available via :meth:`Client.fetch_user`.
"""
if self._banner is None:
return None
return Asset._from_user_banner(self._state, self.id, self._banner)
def accent_colour(self) -> Optional[Colour]:
"""Optional[:class:`Colour`]: Returns the user's accent colour, if applicable.
There is an alias for this named :attr:`accent_color`.
.. versionadded:: 2.0
.. note::
This information is only available via :meth:`Client.fetch_user`.
"""
if self._accent_colour is None:
return None
return Colour(int(self._accent_colour))
def accent_color(self) -> Optional[Colour]:
"""Optional[:class:`Colour`]: Returns the user's accent color, if applicable.
There is an alias for this named :attr:`accent_colour`.
.. versionadded:: 2.0
.. note::
This information is only available via :meth:`Client.fetch_user`.
"""
return self.accent_colour
def colour(self) -> Colour:
""":class:`Colour`: A property that returns a colour denoting the rendered colour
for the user. This always returns :meth:`Colour.default`.
There is an alias for this named :attr:`color`.
"""
return Colour.default()
def color(self) -> Colour:
""":class:`Colour`: A property that returns a color denoting the rendered color
for the user. This always returns :meth:`Colour.default`.
There is an alias for this named :attr:`colour`.
"""
return self.colour
def mention(self) -> str:
""":class:`str`: Returns a string that allows you to mention the given user."""
return f"<@{self.id}>"
def created_at(self) -> datetime:
""":class:`datetime.datetime`: Returns the user's creation time in UTC.
This is when the user's Discord account was created.
"""
return snowflake_time(self.id)
def display_name(self) -> str:
""":class:`str`: Returns the user's display name.
For regular users this is just their username, but
if they have a guild specific nickname then that
is returned instead.
"""
return self.name
def mentioned_in(self, message: Message) -> bool:
"""Checks if the user is mentioned in the specified message.
Parameters
----------
message: :class:`Message`
The message to check if you're mentioned in.
Returns
-------
:class:`bool`
Indicates if the user is mentioned in the message.
"""
if message.mention_everyone:
return True
return any(user.id == self.id for user in message.mentions)
class User(BaseUser, abc.Messageable):
"""Represents a Discord user.
.. container:: operations
.. describe:: x == y
Checks if two users are equal.
.. describe:: x != y
Checks if two users are not equal.
.. describe:: hash(x)
Return the user's hash.
.. describe:: str(x)
Returns the user's name with discriminator.
Attributes
----------
name: :class:`str`
The user's username.
id: :class:`int`
The user's unique ID.
global_name: Optional[:class:`str`]
The user's default name, if any.
..versionadded: 2.6
discriminator: :class:`str`
The user's discriminator.
.. warning::
This field is deprecated, and will only return if the user has not yet migrated to the
new `username <https://dis.gd/usernames>`_ update.
.. deprecated:: 2.6
bot: :class:`bool`
Specifies if the user is a bot account.
system: :class:`bool`
Specifies if the user is a system user (i.e. represents Discord officially).
"""
__slots__ = ("_stored",)
def __init__(
self, *, state: ConnectionState, data: Union[PartialUserPayload, UserPayload]
) -> None:
super().__init__(state=state, data=data)
self._stored: bool = False
def __repr__(self) -> str:
return (
f"<User id={self.id} name={self.name!r} global_name={self.global_name!r}"
+ (f" discriminator={self.discriminator!r}" if self.discriminator != "0" else "")
+ f" bot={self.bot}>"
)
def __del__(self) -> None:
try:
if self._stored:
self._state.deref_user(self.id)
except Exception:
pass
def _copy(cls, user: User):
self = super()._copy(user)
self._stored = False
return self
async def _get_channel(self) -> DMChannel:
return await self.create_dm()
def dm_channel(self) -> Optional[DMChannel]:
"""Optional[:class:`DMChannel`]: Returns the channel associated with this user if it exists.
If this returns ``None``, you can create a DM channel by calling the
:meth:`create_dm` coroutine function.
"""
return self._state._get_private_channel_by_user(self.id)
def mutual_guilds(self) -> List[Guild]:
"""List[:class:`Guild`]: The guilds that the user shares with the client.
.. note::
This will only return mutual guilds within the client's internal cache.
.. versionadded:: 1.7
"""
return [guild for guild in self._state._guilds.values() if guild.get_member(self.id)]
async def create_dm(self) -> DMChannel:
"""|coro|
Creates a :class:`DMChannel` with this user.
This should be rarely called, as this is done transparently for most
people.
Returns
-------
:class:`.DMChannel`
The channel that was created.
"""
found = self.dm_channel
if found is not None:
return found
state = self._state
data: DMChannelPayload = await state.http.start_private_message(self.id)
return state.add_dm_channel(data)
class User(PartialUser, total=False):
bot: bool
system: bool
mfa_enabled: bool
local: str
verified: bool
email: Optional[str]
flags: int
premium_type: PremiumType
public_flags: int
global_name: Optional[str]
def flatten_user(cls):
for attr, value in itertools.chain(BaseUser.__dict__.items(), User.__dict__.items()):
# ignore private/special methods
if attr.startswith("_"):
continue
# don't override what we already have
if attr in cls.__dict__:
continue
# if it's a slotted attribute or a property, redirect it
# slotted members are implemented as member_descriptors in Type.__dict__
if not hasattr(value, "__annotations__"):
getter = attrgetter("_user." + attr)
setattr(cls, attr, property(getter, doc=f"Equivalent to :attr:`User.{attr}`"))
else:
# Technically, this can also use attrgetter
# However I'm not sure how I feel about "functions" returning properties
# It probably breaks something in Sphinx.
# probably a member function by now
def generate_function(x, value):
# We want sphinx to properly show coroutine functions as coroutines
if asyncio.iscoroutinefunction(value):
async def general(self, *args, **kwargs): # type: ignore
return await getattr(self._user, x)(*args, **kwargs)
else:
def general(self, *args, **kwargs):
return getattr(self._user, x)(*args, **kwargs)
general.__name__ = x
return general
func = generate_function(attr, value)
func = utils.copy_doc(value)(func)
setattr(cls, attr, func)
return cls | null |
160,994 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, Iterator, Optional, Set, Tuple
from .flags import BaseFlags, alias_flag_value, fill_with_flags, flag_value
class permission_alias(alias_flag_value):
alias: str
def make_permission_alias(alias: str) -> Callable[[Callable[[Any], int]], permission_alias]:
def decorator(func: Callable[[Any], int]) -> permission_alias:
ret = permission_alias(func)
ret.alias = alias
return ret
return decorator | null |
160,995 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, Iterator, Optional, Set, Tuple
from .flags import BaseFlags, alias_flag_value, fill_with_flags, flag_value
class permission_alias(alias_flag_value):
class Permissions(BaseFlags):
def __init__(self, permissions: int = 0, **kwargs: bool) -> None:
def is_subset(self, other: Permissions) -> bool:
def is_superset(self, other: Permissions) -> bool:
def is_strict_subset(self, other: Permissions) -> bool:
def is_strict_superset(self, other: Permissions) -> bool:
def none(cls) -> Self:
def all(cls) -> Self:
def all_channel(cls) -> Self:
def general(cls) -> Self:
def membership(cls) -> Self:
def text(cls) -> Self:
def voice(cls) -> Self:
def stage(cls) -> Self:
def stage_moderator(cls) -> Self:
def advanced(cls) -> Self:
def update(self, **kwargs: bool) -> None:
def handle_overwrite(self, allow: int, deny: int) -> None:
def create_instant_invite(self) -> int:
def kick_members(self) -> int:
def ban_members(self) -> int:
def administrator(self) -> int:
def manage_channels(self) -> int:
def manage_guild(self) -> int:
def add_reactions(self) -> int:
def view_audit_log(self) -> int:
def priority_speaker(self) -> int:
def stream(self) -> int:
def read_messages(self) -> int:
def view_channel(self) -> int:
def send_messages(self) -> int:
def send_tts_messages(self) -> int:
def manage_messages(self) -> int:
def embed_links(self) -> int:
def attach_files(self) -> int:
def read_message_history(self) -> int:
def mention_everyone(self) -> int:
def external_emojis(self) -> int:
def use_external_emojis(self) -> int:
def view_guild_insights(self) -> int:
def connect(self) -> int:
def speak(self) -> int:
def mute_members(self) -> int:
def deafen_members(self) -> int:
def move_members(self) -> int:
def use_voice_activation(self) -> int:
def change_nickname(self) -> int:
def manage_nicknames(self) -> int:
def manage_roles(self) -> int:
def manage_permissions(self) -> int:
def manage_webhooks(self) -> int:
def manage_emojis(self) -> int:
def manage_emojis_and_stickers(self) -> int:
def use_slash_commands(self) -> int:
def request_to_speak(self) -> int:
def manage_events(self) -> int:
def manage_threads(self) -> int:
def create_public_threads(self) -> int:
def create_private_threads(self) -> int:
def external_stickers(self) -> int:
def use_external_stickers(self) -> int:
def send_messages_in_threads(self) -> int:
def start_embedded_activities(self) -> int:
def moderate_members(self) -> int:
class flag_value:
def __init__(self, func: Callable[[Any], int]) -> None:
def __get__(self, instance: None, owner: Type[BF]) -> Self:
def __get__(self, instance: BF, owner: Type[BF]) -> bool:
def __get__(self, instance: Optional[BF], owner: Type[BF]) -> Any:
def __set__(self, instance: BaseFlags, value: bool) -> None:
def __repr__(self) -> str:
def _augment_from_permissions(cls):
cls.VALID_NAMES = set(Permissions.VALID_FLAGS)
aliases = set()
# make descriptors for all the valid names and aliases
for name, value in Permissions.__dict__.items():
if isinstance(value, permission_alias):
key = value.alias
aliases.add(name)
elif isinstance(value, flag_value):
key = name
else:
continue
# god bless Python
def getter(self, x=key):
return self._values.get(x)
def setter(self, value, x=key) -> None:
self._set(x, value)
prop = property(getter, setter)
setattr(cls, name, prop)
cls.PURE_FLAGS = cls.VALID_NAMES - aliases
return cls | null |
160,996 | from __future__ import annotations
import asyncio
import contextlib
import logging
import signal
import sys
import traceback
import warnings
from typing import (
TYPE_CHECKING,
Any,
Callable,
Coroutine,
Dict,
Generator,
Iterable,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
import aiohttp
from . import utils
from .activity import ActivityTypes, BaseActivity, create_activity
from .appinfo import AppInfo
from .application_command import message_command, slash_command, user_command
from .backoff import ExponentialBackoff
from .channel import PartialMessageable, _threaded_channel_factory
from .emoji import Emoji
from .enums import (
ApplicationCommandType,
ChannelType,
InteractionType,
Status,
VoiceRegion,
)
from .errors import *
from .flags import ApplicationFlags, Intents
from .gateway import *
from .guild import Guild
from .guild_preview import GuildPreview
from .http import HTTPClient
from .interactions import Interaction
from .invite import Invite
from .iterators import GuildIterator
from .mentions import AllowedMentions
from .object import Object
from .stage_instance import StageInstance
from .state import ConnectionState
from .sticker import GuildSticker, StandardSticker, StickerPack, _sticker_factory
from .template import Template
from .threads import Thread
from .types.interactions import ApplicationCommandInteractionData
from .ui.modal import Modal
from .ui.view import View
from .user import ClientUser, User
from .utils import MISSING
from .voice_client import VoiceClient
from .webhook import Webhook
from .widget import Widget
_log = logging.getLogger(__name__)
def _cancel_tasks(loop: asyncio.AbstractEventLoop) -> None:
tasks = {t for t in asyncio.all_tasks(loop=loop) if not t.done()}
if not tasks:
return
_log.info("Cleaning up after %d tasks.", len(tasks))
for task in tasks:
task.cancel()
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
_log.info("All tasks finished cancelling.")
for task in tasks:
if task.cancelled():
continue
if task.exception() is not None:
loop.call_exception_handler(
{
"message": "Unhandled exception during Client.run shutdown.",
"exception": task.exception(),
"task": task,
}
)
import asyncio
_log = logging.getLogger(__name__)
def _cleanup_loop(loop: asyncio.AbstractEventLoop) -> None:
try:
_cancel_tasks(loop)
loop.run_until_complete(loop.shutdown_asyncgens())
finally:
_log.info("Closing the event loop.")
loop.close() | null |
160,997 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
r"""Represents an Audit Log entry.
You retrieve these via :meth:`Guild.audit_logs`.
.. container:: operations
.. describe:: x == y
Checks if two entries are equal.
.. describe:: x != y
Checks if two entries are not equal.
.. describe:: hash(x)
Returns the entry's hash.
.. versionchanged:: 1.7
Audit log entries are now comparable and hashable.
Attributes
----------
action: :class:`AuditLogAction`
The action that was done.
user: :class:`abc.User`
The user who initiated this action. Usually a :class:`Member`\, unless gone
then it's a :class:`User`.
id: :class:`int`
The entry ID.
target: Any
The target that got changed. The exact type of this depends on
the action being done.
reason: Optional[:class:`str`]
The reason this action was done.
extra: Any
Extra information that this entry has that might be useful.
For most actions, this is ``None``. However in some cases it
contains extra information. See :class:`AuditLogAction` for
which actions have this field filled out.
"""
extra: Union[
_AuditLogProxyMemberPrune,
_AuditLogProxyMemberMoveOrMessageDelete,
_AuditLogProxyMemberDisconnect,
_AuditLogProxyPinAction,
_AuditLogProxyStageInstanceAction,
_AuditLogProxyAutoModerationBlockMessage,
Member,
User,
None,
Role,
]
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
self._state = guild._state
self.guild = guild
self._auto_moderation_rules = auto_moderation_rules
self._users = users
self._from_data(data)
def _from_data(self, data: AuditLogEntryPayload) -> None:
self.action = enums.try_enum(enums.AuditLogAction, data["action_type"])
self.id = int(data["id"])
# this key is technically not usually present
self.reason = data.get("reason")
self.extra = data.get("options", {}) # type: ignore
# I gave up trying to fix this
elems: Dict[str, Any] = {}
channel_id = int(self.extra["channel_id"]) if self.extra.get("channel_id", None) else None
if isinstance(self.action, enums.AuditLogAction) and self.extra:
if self.action is enums.AuditLogAction.member_prune:
# member prune has two keys with useful information
self.extra = type( # type: ignore
"_AuditLogProxy", (), {k: int(v) for k, v in self.extra.items()} # type: ignore
)()
elif (
self.action is enums.AuditLogAction.member_move
or self.action is enums.AuditLogAction.message_delete
):
elems = {
"count": int(self.extra["count"]),
}
elif self.action is enums.AuditLogAction.member_disconnect:
# The member disconnect action has a dict with some information
elems = {
"count": int(self.extra["count"]),
}
elif self.action.name.endswith("pin"):
# the pin actions have a dict with some information
elems = {
"message_id": int(self.extra["message_id"]),
}
elif self.action.name.startswith("overwrite_"):
# the overwrite_ actions have a dict with some information
instance_id = int(self.extra["id"])
the_type = self.extra.get("type")
if the_type == "1":
self.extra = self._get_member(instance_id)
elif the_type == "0":
role = self.guild.get_role(instance_id)
if role is None:
role = Object(id=instance_id)
role.name = self.extra.get("role_name") # type: ignore
self.extra = role # type: ignore
elif self.action.name.startswith("stage_instance"):
channel_id = int(self.extra["channel_id"])
elems = {"channel": self.guild.get_channel(channel_id) or Object(id=channel_id)}
elif (
self.action is enums.AuditLogAction.auto_moderation_block_message
or self.action is enums.AuditLogAction.auto_moderation_flag_to_channel
or self.action is enums.AuditLogAction.auto_moderation_user_communication_disabled
):
elems = {
"rule_name": self.extra["auto_moderation_rule_name"],
"rule_trigger_type": enums.try_enum(
enums.AutoModerationTriggerType,
int(self.extra["auto_moderation_rule_trigger_type"]),
),
}
# this just gets automatically filled in if present, this way prevents crashes if channel_id is None
if channel_id and self.action:
elems["channel"] = self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id)
if type(self.extra) is dict:
self.extra = type("_AuditLogProxy", (), elems)() # type: ignore
# this key is not present when the above is present, typically.
# It's a list of { new_value: a, old_value: b, key: c }
# where new_value and old_value are not guaranteed to be there depending
# on the action type, so let's just fetch it for now and only turn it
# into meaningful data when requested
self._changes = data.get("changes", [])
self.user = self._get_member(utils.get_as_snowflake(data, "user_id")) # type: ignore
self._target_id = utils.get_as_snowflake(data, "target_id")
def _get_member(self, user_id: int) -> Union[Member, User, None]:
return self.guild.get_member(user_id) or self._users.get(user_id)
def __repr__(self) -> str:
return f"<AuditLogEntry id={self.id} action={self.action} user={self.user!r}>"
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the entry's creation time in UTC."""
return utils.snowflake_time(self.id)
def target(self) -> AuditTarget:
try:
converter = getattr(self, "_convert_target_" + str(self.action.target_type))
except AttributeError:
if self._target_id is None:
return None
return Object(id=self._target_id)
else:
return converter(self._target_id)
def category(self) -> Optional[enums.AuditLogActionCategory]:
"""Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable."""
return self.action.category
def changes(self) -> AuditLogChanges:
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj
def before(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's prior state."""
return self.changes.before
def after(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's subsequent state."""
return self.changes.after
def _convert_target_guild(self, target_id: int) -> Guild:
return self.guild
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
return self.guild.get_channel(target_id) or Object(id=target_id)
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
return self.guild.get_role(target_id) or Object(id=target_id)
def _convert_target_invite(self, target_id: int) -> Invite:
# invites have target_id set to null
# so figure out which change has the full invite data
changeset = self.before if self.action is enums.AuditLogAction.invite_delete else self.after
fake_payload = {
"max_age": changeset.max_age,
"max_uses": changeset.max_uses,
"code": changeset.code,
"temporary": changeset.temporary,
"uses": changeset.uses,
}
obj = Invite(state=self._state, data=fake_payload, guild=self.guild, channel=changeset.channel) # type: ignore
with contextlib.suppress(AttributeError):
obj.inviter = changeset.inviter
return obj
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
return self._state.get_emoji(target_id) or Object(id=target_id)
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
return self.guild.get_stage_instance(target_id) or Object(id=target_id)
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
return self._state.get_sticker(target_id) or Object(id=target_id)
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
return self.guild.get_thread(target_id) or Object(id=target_id)
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
return self._auto_moderation_rules.get(rule_id) or Object(id=rule_id)
class Permissions(BaseFlags):
"""Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual
bits using the properties as if they were regular bools. This allows
you to edit permissions.
.. versionchanged:: 1.3
You can now use keyword arguments to initialize :class:`Permissions`
similar to :meth:`update`.
.. container:: operations
.. describe:: x == y
Checks if two permissions are equal.
.. describe:: x != y
Checks if two permissions are not equal.
.. describe:: x <= y
Checks if a permission is a subset of another permission.
.. describe:: x >= y
Checks if a permission is a superset of another permission.
.. describe:: x < y
Checks if a permission is a strict subset of another permission.
.. describe:: x > y
Checks if a permission is a strict superset of another permission.
.. describe:: hash(x)
Return the permission's hash.
.. describe:: iter(x)
Returns an iterator of ``(perm, value)`` pairs. This allows it
to be, for example, constructed as a dict or a list of pairs.
Note that aliases are not shown.
Attributes
----------
value: :class:`int`
The raw value. This value is a bit array field of a 53-bit integer
representing the currently available permissions. You should query
permissions via the properties rather than using this raw value.
"""
__slots__ = ()
def __init__(self, permissions: int = 0, **kwargs: bool) -> None:
if not isinstance(permissions, int):
raise TypeError(
f"Expected int parameter, received {permissions.__class__.__name__} instead."
)
self.value = permissions
for key, value in kwargs.items():
if key not in self.VALID_FLAGS:
raise TypeError(f"{key!r} is not a valid permission name.")
setattr(self, key, value)
def is_subset(self, other: Permissions) -> bool:
"""Returns ``True`` if self has the same or fewer permissions as other."""
if isinstance(other, Permissions):
return (self.value & other.value) == self.value
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}")
def is_superset(self, other: Permissions) -> bool:
"""Returns ``True`` if self has the same or more permissions as other."""
if isinstance(other, Permissions):
return (self.value | other.value) == self.value
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}")
def is_strict_subset(self, other: Permissions) -> bool:
"""Returns ``True`` if the permissions on other are a strict subset of those on self."""
return self.is_subset(other) and self != other
def is_strict_superset(self, other: Permissions) -> bool:
"""Returns ``True`` if the permissions on other are a strict superset of those on self."""
return self.is_superset(other) and self != other
__le__ = is_subset
__ge__ = is_superset
__lt__ = is_strict_subset
__gt__ = is_strict_superset
def none(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
permissions set to ``False``."""
return cls(0)
def all(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
permissions set to ``True``.
"""
return cls(-1)
def all_channel(cls) -> Self:
"""A :class:`Permissions` with all channel-specific permissions set to
``True`` and the guild-specific ones set to ``False``. The guild-specific
permissions are currently:
- :attr:`manage_emojis`
- :attr:`view_audit_log`
- :attr:`view_guild_insights`
- :attr:`manage_guild`
- :attr:`change_nickname`
- :attr:`manage_nicknames`
- :attr:`kick_members`
- :attr:`ban_members`
- :attr:`administrator`
.. versionchanged:: 1.7
Added :attr:`stream`, :attr:`priority_speaker` and :attr:`use_slash_commands` permissions.
.. versionchanged:: 2.0
Added :attr:`create_public_threads`, :attr:`create_private_threads`, :attr:`manage_threads`,
:attr:`use_external_stickers`, :attr:`send_messages_in_threads` and
:attr:`request_to_speak` permissions.
"""
return cls(0b111110110110011111101111111111101010001)
def general(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"General" permissions from the official Discord UI set to ``True``.
.. versionchanged:: 1.7
Permission :attr:`read_messages` is now included in the general permissions, but
permissions :attr:`administrator`, :attr:`create_instant_invite`, :attr:`kick_members`,
:attr:`ban_members`, :attr:`change_nickname` and :attr:`manage_nicknames` are
no longer part of the general permissions.
"""
return cls(0b01110000000010000000010010110000)
def membership(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Membership" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(0b00001100000000000000000000000111)
def text(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Text" permissions from the official Discord UI set to ``True``.
.. versionchanged:: 1.7
Permission :attr:`read_messages` is no longer part of the text permissions.
Added :attr:`use_slash_commands` permission.
.. versionchanged:: 2.0
Added :attr:`create_public_threads`, :attr:`create_private_threads`, :attr:`manage_threads`,
:attr:`send_messages_in_threads` and :attr:`use_external_stickers` permissions.
"""
return cls(0b111110010000000000001111111100001000000)
def voice(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Voice" permissions from the official Discord UI set to ``True``."""
return cls(0b00000011111100000000001100000000)
def stage(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Stage Channel" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(1 << 32)
def stage_moderator(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Stage Moderator" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(0b100000001010000000000000000000000)
def advanced(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Advanced" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(1 << 3)
def update(self, **kwargs: bool) -> None:
r"""Bulk updates this permission object.
Allows you to set multiple attributes by using keyword
arguments. The names must be equivalent to the properties
listed. Extraneous key/value pairs will be silently ignored.
Parameters
----------
\*\*kwargs
A list of key/value pairs to bulk update permissions with.
"""
for key, value in kwargs.items():
if key in self.VALID_FLAGS:
setattr(self, key, value)
def handle_overwrite(self, allow: int, deny: int) -> None:
# Basically this is what's happening here.
# We have an original bit array, e.g. 1010
# Then we have another bit array that is 'denied', e.g. 1111
# And then we have the last one which is 'allowed', e.g. 0101
# We want original OP denied to end up resulting in
# whatever is in denied to be set to 0.
# So 1010 OP 1111 -> 0000
# Then we take this value and look at the allowed values.
# And whatever is allowed is set to 1.
# So 0000 OP2 0101 -> 0101
# The OP is base & ~denied.
# The OP2 is base | allowed.
self.value = (self.value & ~deny) | allow
def create_instant_invite(self) -> int:
""":class:`bool`: Returns ``True`` if the user can create instant invites."""
return 1 << 0
def kick_members(self) -> int:
""":class:`bool`: Returns ``True`` if the user can kick users from the guild."""
return 1 << 1
def ban_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can ban users from the guild."""
return 1 << 2
def administrator(self) -> int:
""":class:`bool`: Returns ``True`` if a user is an administrator. This role overrides all other permissions.
This also bypasses all channel-specific overrides.
"""
return 1 << 3
def manage_channels(self) -> int:
""":class:`bool`: Returns ``True`` if a user can edit, delete, or create channels in the guild.
This also corresponds to the "Manage Channel" channel-specific override."""
return 1 << 4
def manage_guild(self) -> int:
""":class:`bool`: Returns ``True`` if a user can edit guild properties."""
return 1 << 5
def add_reactions(self) -> int:
""":class:`bool`: Returns ``True`` if a user can add reactions to messages."""
return 1 << 6
def view_audit_log(self) -> int:
""":class:`bool`: Returns ``True`` if a user can view the guild's audit log."""
return 1 << 7
def priority_speaker(self) -> int:
""":class:`bool`: Returns ``True`` if a user can be more easily heard while talking."""
return 1 << 8
def stream(self) -> int:
""":class:`bool`: Returns ``True`` if a user can stream in a voice channel."""
return 1 << 9
def read_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can read messages from all or specific text channels."""
return 1 << 10
def view_channel(self) -> int:
""":class:`bool`: An alias for :attr:`read_messages`.
.. versionadded:: 1.3
"""
return 1 << 10
def send_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send messages from all or specific text channels.
This falls under ``Create Posts`` on the UI specifically for Forum Channels.
"""
return 1 << 11
def send_tts_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send TTS messages from all or specific text channels."""
return 1 << 12
def manage_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can delete or pin messages in a text channel.
.. note::
Note that there are currently no ways to edit other people's messages.
"""
return 1 << 13
def embed_links(self) -> int:
""":class:`bool`: Returns ``True`` if a user's messages will automatically be embedded by Discord."""
return 1 << 14
def attach_files(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send files in their messages."""
return 1 << 15
def read_message_history(self) -> int:
""":class:`bool`: Returns ``True`` if a user can read a text channel's previous messages."""
return 1 << 16
def mention_everyone(self) -> int:
""":class:`bool`: Returns ``True`` if a user's @everyone or @here will mention everyone in the text channel."""
return 1 << 17
def external_emojis(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use emojis from other guilds."""
return 1 << 18
def use_external_emojis(self) -> int:
""":class:`bool`: An alias for :attr:`external_emojis`.
.. versionadded:: 1.3
"""
return 1 << 18
def view_guild_insights(self) -> int:
""":class:`bool`: Returns ``True`` if a user can view the guild's insights.
.. versionadded:: 1.3
"""
return 1 << 19
def connect(self) -> int:
""":class:`bool`: Returns ``True`` if a user can connect to a voice channel."""
return 1 << 20
def speak(self) -> int:
""":class:`bool`: Returns ``True`` if a user can speak in a voice channel."""
return 1 << 21
def mute_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can mute other users."""
return 1 << 22
def deafen_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can deafen other users."""
return 1 << 23
def move_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can move users between other voice channels."""
return 1 << 24
def use_voice_activation(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use voice activation in voice channels."""
return 1 << 25
def change_nickname(self) -> int:
""":class:`bool`: Returns ``True`` if a user can change their nickname in the guild."""
return 1 << 26
def manage_nicknames(self) -> int:
""":class:`bool`: Returns ``True`` if a user can change other user's nickname in the guild."""
return 1 << 27
def manage_roles(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create or edit roles less than their role's position.
This also corresponds to the "Manage Permissions" channel-specific override.
"""
return 1 << 28
def manage_permissions(self) -> int:
""":class:`bool`: An alias for :attr:`manage_roles`.
.. versionadded:: 1.3
"""
return 1 << 28
def manage_webhooks(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create, edit, or delete webhooks."""
return 1 << 29
def manage_emojis(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create, edit, or delete emojis."""
return 1 << 30
def manage_emojis_and_stickers(self) -> int:
""":class:`bool`: An alias for :attr:`manage_emojis`.
.. versionadded:: 2.0
"""
return 1 << 30
def use_slash_commands(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use slash commands.
.. versionadded:: 1.7
"""
return 1 << 31
def request_to_speak(self) -> int:
""":class:`bool`: Returns ``True`` if a user can request to speak in a stage channel.
.. versionadded:: 1.7
"""
return 1 << 32
def manage_events(self) -> int:
""":class:`bool`: Returns ``True`` if a user can manage guild events.
.. versionadded:: 2.0
"""
return 1 << 33
def manage_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can manage threads.
.. versionadded:: 2.0
"""
return 1 << 34
def create_public_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create public threads.
.. versionadded:: 2.0
"""
return 1 << 35
def create_private_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create private threads.
.. versionadded:: 2.0
"""
return 1 << 36
def external_stickers(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use stickers from other guilds.
.. versionadded:: 2.0
"""
return 1 << 37
def use_external_stickers(self) -> int:
""":class:`bool`: An alias for :attr:`external_stickers`.
.. versionadded:: 2.0
"""
return 1 << 37
def send_messages_in_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send messages in threads.
This falls under ``Send Messages in Posts`` on the UI specifically for Forum channels.
.. versionadded:: 2.0
"""
return 1 << 38
def start_embedded_activities(self) -> int:
""":class:`bool`: Returns ``True`` if a user can launch activities in a voice channel.
.. versionadded:: 2.0
"""
return 1 << 39
def moderate_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can moderate members (add timeouts).
Referred to as ``Timeout Members`` in the discord client.
.. versionadded:: 2.0
"""
return 1 << 40
def _transform_permissions(_entry: AuditLogEntry, data: str) -> Permissions:
return Permissions(int(data)) | null |
160,998 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
def _from_data(self, data: AuditLogEntryPayload) -> None:
def _get_member(self, user_id: int) -> Union[Member, User, None]:
def __repr__(self) -> str:
def created_at(self) -> datetime.datetime:
def target(self) -> AuditTarget:
def category(self) -> Optional[enums.AuditLogActionCategory]:
def changes(self) -> AuditLogChanges:
def before(self) -> AuditLogDiff:
def after(self) -> AuditLogDiff:
def _convert_target_guild(self, target_id: int) -> Guild:
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
def _convert_target_invite(self, target_id: int) -> Invite:
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
class Colour:
def __init__(self, value: int) -> None:
def _get_byte(self, byte: int) -> int:
def __eq__(self, other: Any) -> bool:
def __ne__(self, other: Any) -> bool:
def __str__(self) -> str:
def __int__(self) -> int:
def __repr__(self) -> str:
def __hash__(self) -> int:
def r(self) -> int:
def g(self) -> int:
def b(self) -> int:
def to_rgb(self) -> Tuple[int, int, int]:
def from_rgb(cls, r: int, g: int, b: int) -> Self:
def from_hsv(cls, h: float, s: float, v: float) -> Self:
def default(cls) -> Self:
def random(cls, *, seed: Optional[Union[int, str, float, bytes, bytearray]] = None) -> Self:
def teal(cls) -> Self:
def dark_teal(cls) -> Self:
def brand_green(cls) -> Self:
def green(cls) -> Self:
def dark_green(cls) -> Self:
def blue(cls) -> Self:
def dark_blue(cls) -> Self:
def purple(cls) -> Self:
def dark_purple(cls) -> Self:
def magenta(cls) -> Self:
def dark_magenta(cls) -> Self:
def gold(cls) -> Self:
def dark_gold(cls) -> Self:
def orange(cls) -> Self:
def dark_orange(cls) -> Self:
def brand_red(cls) -> Self:
def red(cls) -> Self:
def dark_red(cls) -> Self:
def lighter_grey(cls) -> Self:
def dark_grey(cls) -> Self:
def light_grey(cls) -> Self:
def darker_grey(cls) -> Self:
def og_blurple(cls) -> Self:
def blurple(cls) -> Self:
def greyple(cls) -> Self:
def dark_theme(cls) -> Self:
def fuchsia(cls) -> Self:
def yellow(cls) -> Self:
def _transform_color(_entry: AuditLogEntry, data: int) -> Colour:
return Colour(data) | null |
160,999 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
def _from_data(self, data: AuditLogEntryPayload) -> None:
def _get_member(self, user_id: int) -> Union[Member, User, None]:
def __repr__(self) -> str:
def created_at(self) -> datetime.datetime:
def target(self) -> AuditTarget:
def category(self) -> Optional[enums.AuditLogActionCategory]:
def changes(self) -> AuditLogChanges:
def before(self) -> AuditLogDiff:
def after(self) -> AuditLogDiff:
def _convert_target_guild(self, target_id: int) -> Guild:
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
def _convert_target_invite(self, target_id: int) -> Invite:
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
Snowflake = Union[str, int]
def _transform_snowflake(_entry: AuditLogEntry, data: Snowflake) -> int:
return int(data) | null |
161,000 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
r"""Represents an Audit Log entry.
You retrieve these via :meth:`Guild.audit_logs`.
.. container:: operations
.. describe:: x == y
Checks if two entries are equal.
.. describe:: x != y
Checks if two entries are not equal.
.. describe:: hash(x)
Returns the entry's hash.
.. versionchanged:: 1.7
Audit log entries are now comparable and hashable.
Attributes
----------
action: :class:`AuditLogAction`
The action that was done.
user: :class:`abc.User`
The user who initiated this action. Usually a :class:`Member`\, unless gone
then it's a :class:`User`.
id: :class:`int`
The entry ID.
target: Any
The target that got changed. The exact type of this depends on
the action being done.
reason: Optional[:class:`str`]
The reason this action was done.
extra: Any
Extra information that this entry has that might be useful.
For most actions, this is ``None``. However in some cases it
contains extra information. See :class:`AuditLogAction` for
which actions have this field filled out.
"""
extra: Union[
_AuditLogProxyMemberPrune,
_AuditLogProxyMemberMoveOrMessageDelete,
_AuditLogProxyMemberDisconnect,
_AuditLogProxyPinAction,
_AuditLogProxyStageInstanceAction,
_AuditLogProxyAutoModerationBlockMessage,
Member,
User,
None,
Role,
]
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
self._state = guild._state
self.guild = guild
self._auto_moderation_rules = auto_moderation_rules
self._users = users
self._from_data(data)
def _from_data(self, data: AuditLogEntryPayload) -> None:
self.action = enums.try_enum(enums.AuditLogAction, data["action_type"])
self.id = int(data["id"])
# this key is technically not usually present
self.reason = data.get("reason")
self.extra = data.get("options", {}) # type: ignore
# I gave up trying to fix this
elems: Dict[str, Any] = {}
channel_id = int(self.extra["channel_id"]) if self.extra.get("channel_id", None) else None
if isinstance(self.action, enums.AuditLogAction) and self.extra:
if self.action is enums.AuditLogAction.member_prune:
# member prune has two keys with useful information
self.extra = type( # type: ignore
"_AuditLogProxy", (), {k: int(v) for k, v in self.extra.items()} # type: ignore
)()
elif (
self.action is enums.AuditLogAction.member_move
or self.action is enums.AuditLogAction.message_delete
):
elems = {
"count": int(self.extra["count"]),
}
elif self.action is enums.AuditLogAction.member_disconnect:
# The member disconnect action has a dict with some information
elems = {
"count": int(self.extra["count"]),
}
elif self.action.name.endswith("pin"):
# the pin actions have a dict with some information
elems = {
"message_id": int(self.extra["message_id"]),
}
elif self.action.name.startswith("overwrite_"):
# the overwrite_ actions have a dict with some information
instance_id = int(self.extra["id"])
the_type = self.extra.get("type")
if the_type == "1":
self.extra = self._get_member(instance_id)
elif the_type == "0":
role = self.guild.get_role(instance_id)
if role is None:
role = Object(id=instance_id)
role.name = self.extra.get("role_name") # type: ignore
self.extra = role # type: ignore
elif self.action.name.startswith("stage_instance"):
channel_id = int(self.extra["channel_id"])
elems = {"channel": self.guild.get_channel(channel_id) or Object(id=channel_id)}
elif (
self.action is enums.AuditLogAction.auto_moderation_block_message
or self.action is enums.AuditLogAction.auto_moderation_flag_to_channel
or self.action is enums.AuditLogAction.auto_moderation_user_communication_disabled
):
elems = {
"rule_name": self.extra["auto_moderation_rule_name"],
"rule_trigger_type": enums.try_enum(
enums.AutoModerationTriggerType,
int(self.extra["auto_moderation_rule_trigger_type"]),
),
}
# this just gets automatically filled in if present, this way prevents crashes if channel_id is None
if channel_id and self.action:
elems["channel"] = self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id)
if type(self.extra) is dict:
self.extra = type("_AuditLogProxy", (), elems)() # type: ignore
# this key is not present when the above is present, typically.
# It's a list of { new_value: a, old_value: b, key: c }
# where new_value and old_value are not guaranteed to be there depending
# on the action type, so let's just fetch it for now and only turn it
# into meaningful data when requested
self._changes = data.get("changes", [])
self.user = self._get_member(utils.get_as_snowflake(data, "user_id")) # type: ignore
self._target_id = utils.get_as_snowflake(data, "target_id")
def _get_member(self, user_id: int) -> Union[Member, User, None]:
return self.guild.get_member(user_id) or self._users.get(user_id)
def __repr__(self) -> str:
return f"<AuditLogEntry id={self.id} action={self.action} user={self.user!r}>"
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the entry's creation time in UTC."""
return utils.snowflake_time(self.id)
def target(self) -> AuditTarget:
try:
converter = getattr(self, "_convert_target_" + str(self.action.target_type))
except AttributeError:
if self._target_id is None:
return None
return Object(id=self._target_id)
else:
return converter(self._target_id)
def category(self) -> Optional[enums.AuditLogActionCategory]:
"""Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable."""
return self.action.category
def changes(self) -> AuditLogChanges:
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj
def before(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's prior state."""
return self.changes.before
def after(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's subsequent state."""
return self.changes.after
def _convert_target_guild(self, target_id: int) -> Guild:
return self.guild
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
return self.guild.get_channel(target_id) or Object(id=target_id)
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
return self.guild.get_role(target_id) or Object(id=target_id)
def _convert_target_invite(self, target_id: int) -> Invite:
# invites have target_id set to null
# so figure out which change has the full invite data
changeset = self.before if self.action is enums.AuditLogAction.invite_delete else self.after
fake_payload = {
"max_age": changeset.max_age,
"max_uses": changeset.max_uses,
"code": changeset.code,
"temporary": changeset.temporary,
"uses": changeset.uses,
}
obj = Invite(state=self._state, data=fake_payload, guild=self.guild, channel=changeset.channel) # type: ignore
with contextlib.suppress(AttributeError):
obj.inviter = changeset.inviter
return obj
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
return self._state.get_emoji(target_id) or Object(id=target_id)
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
return self.guild.get_stage_instance(target_id) or Object(id=target_id)
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
return self._state.get_sticker(target_id) or Object(id=target_id)
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
return self.guild.get_thread(target_id) or Object(id=target_id)
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
return self._auto_moderation_rules.get(rule_id) or Object(id=rule_id)
class Object(Hashable):
"""Represents a generic Discord object.
The purpose of this class is to allow you to create 'miniature'
versions of data classes if you want to pass in just an ID. Most functions
that take in a specific data class with an ID can also take in this class
as a substitute instead. Note that even though this is the case, not all
objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received
in :dpyissue:`strange order <21>` and when such events happened you would
receive this class rather than the actual data class. These cases are
extremely rare.
.. container:: operations
.. describe:: x == y
Checks if two objects are equal.
.. describe:: x != y
Checks if two objects are not equal.
.. describe:: hash(x)
Returns the object's hash.
Attributes
----------
id: :class:`int`
The ID of the object.
"""
def __init__(self, id: SupportsIntCast) -> None:
try:
id = int(id)
except ValueError:
raise TypeError(
f"id parameter must be convertable to int not {id.__class__!r}"
) from None
else:
self.id = id
def __repr__(self) -> str:
return f"<Object id={self.id!r}>"
def __int__(self) -> int:
return self.id
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the snowflake's creation time in UTC."""
return utils.snowflake_time(self.id)
Snowflake = Union[str, int]
def _transform_channel(
entry: AuditLogEntry, data: Optional[Snowflake]
) -> Optional[Union[abc.GuildChannel, Object]]:
if data is None:
return None
return entry.guild.get_channel(int(data)) or Object(id=data) | null |
161,001 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
r"""Represents an Audit Log entry.
You retrieve these via :meth:`Guild.audit_logs`.
.. container:: operations
.. describe:: x == y
Checks if two entries are equal.
.. describe:: x != y
Checks if two entries are not equal.
.. describe:: hash(x)
Returns the entry's hash.
.. versionchanged:: 1.7
Audit log entries are now comparable and hashable.
Attributes
----------
action: :class:`AuditLogAction`
The action that was done.
user: :class:`abc.User`
The user who initiated this action. Usually a :class:`Member`\, unless gone
then it's a :class:`User`.
id: :class:`int`
The entry ID.
target: Any
The target that got changed. The exact type of this depends on
the action being done.
reason: Optional[:class:`str`]
The reason this action was done.
extra: Any
Extra information that this entry has that might be useful.
For most actions, this is ``None``. However in some cases it
contains extra information. See :class:`AuditLogAction` for
which actions have this field filled out.
"""
extra: Union[
_AuditLogProxyMemberPrune,
_AuditLogProxyMemberMoveOrMessageDelete,
_AuditLogProxyMemberDisconnect,
_AuditLogProxyPinAction,
_AuditLogProxyStageInstanceAction,
_AuditLogProxyAutoModerationBlockMessage,
Member,
User,
None,
Role,
]
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
self._state = guild._state
self.guild = guild
self._auto_moderation_rules = auto_moderation_rules
self._users = users
self._from_data(data)
def _from_data(self, data: AuditLogEntryPayload) -> None:
self.action = enums.try_enum(enums.AuditLogAction, data["action_type"])
self.id = int(data["id"])
# this key is technically not usually present
self.reason = data.get("reason")
self.extra = data.get("options", {}) # type: ignore
# I gave up trying to fix this
elems: Dict[str, Any] = {}
channel_id = int(self.extra["channel_id"]) if self.extra.get("channel_id", None) else None
if isinstance(self.action, enums.AuditLogAction) and self.extra:
if self.action is enums.AuditLogAction.member_prune:
# member prune has two keys with useful information
self.extra = type( # type: ignore
"_AuditLogProxy", (), {k: int(v) for k, v in self.extra.items()} # type: ignore
)()
elif (
self.action is enums.AuditLogAction.member_move
or self.action is enums.AuditLogAction.message_delete
):
elems = {
"count": int(self.extra["count"]),
}
elif self.action is enums.AuditLogAction.member_disconnect:
# The member disconnect action has a dict with some information
elems = {
"count": int(self.extra["count"]),
}
elif self.action.name.endswith("pin"):
# the pin actions have a dict with some information
elems = {
"message_id": int(self.extra["message_id"]),
}
elif self.action.name.startswith("overwrite_"):
# the overwrite_ actions have a dict with some information
instance_id = int(self.extra["id"])
the_type = self.extra.get("type")
if the_type == "1":
self.extra = self._get_member(instance_id)
elif the_type == "0":
role = self.guild.get_role(instance_id)
if role is None:
role = Object(id=instance_id)
role.name = self.extra.get("role_name") # type: ignore
self.extra = role # type: ignore
elif self.action.name.startswith("stage_instance"):
channel_id = int(self.extra["channel_id"])
elems = {"channel": self.guild.get_channel(channel_id) or Object(id=channel_id)}
elif (
self.action is enums.AuditLogAction.auto_moderation_block_message
or self.action is enums.AuditLogAction.auto_moderation_flag_to_channel
or self.action is enums.AuditLogAction.auto_moderation_user_communication_disabled
):
elems = {
"rule_name": self.extra["auto_moderation_rule_name"],
"rule_trigger_type": enums.try_enum(
enums.AutoModerationTriggerType,
int(self.extra["auto_moderation_rule_trigger_type"]),
),
}
# this just gets automatically filled in if present, this way prevents crashes if channel_id is None
if channel_id and self.action:
elems["channel"] = self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id)
if type(self.extra) is dict:
self.extra = type("_AuditLogProxy", (), elems)() # type: ignore
# this key is not present when the above is present, typically.
# It's a list of { new_value: a, old_value: b, key: c }
# where new_value and old_value are not guaranteed to be there depending
# on the action type, so let's just fetch it for now and only turn it
# into meaningful data when requested
self._changes = data.get("changes", [])
self.user = self._get_member(utils.get_as_snowflake(data, "user_id")) # type: ignore
self._target_id = utils.get_as_snowflake(data, "target_id")
def _get_member(self, user_id: int) -> Union[Member, User, None]:
return self.guild.get_member(user_id) or self._users.get(user_id)
def __repr__(self) -> str:
return f"<AuditLogEntry id={self.id} action={self.action} user={self.user!r}>"
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the entry's creation time in UTC."""
return utils.snowflake_time(self.id)
def target(self) -> AuditTarget:
try:
converter = getattr(self, "_convert_target_" + str(self.action.target_type))
except AttributeError:
if self._target_id is None:
return None
return Object(id=self._target_id)
else:
return converter(self._target_id)
def category(self) -> Optional[enums.AuditLogActionCategory]:
"""Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable."""
return self.action.category
def changes(self) -> AuditLogChanges:
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj
def before(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's prior state."""
return self.changes.before
def after(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's subsequent state."""
return self.changes.after
def _convert_target_guild(self, target_id: int) -> Guild:
return self.guild
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
return self.guild.get_channel(target_id) or Object(id=target_id)
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
return self.guild.get_role(target_id) or Object(id=target_id)
def _convert_target_invite(self, target_id: int) -> Invite:
# invites have target_id set to null
# so figure out which change has the full invite data
changeset = self.before if self.action is enums.AuditLogAction.invite_delete else self.after
fake_payload = {
"max_age": changeset.max_age,
"max_uses": changeset.max_uses,
"code": changeset.code,
"temporary": changeset.temporary,
"uses": changeset.uses,
}
obj = Invite(state=self._state, data=fake_payload, guild=self.guild, channel=changeset.channel) # type: ignore
with contextlib.suppress(AttributeError):
obj.inviter = changeset.inviter
return obj
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
return self._state.get_emoji(target_id) or Object(id=target_id)
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
return self.guild.get_stage_instance(target_id) or Object(id=target_id)
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
return self._state.get_sticker(target_id) or Object(id=target_id)
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
return self.guild.get_thread(target_id) or Object(id=target_id)
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
return self._auto_moderation_rules.get(rule_id) or Object(id=rule_id)
class Member(abc.Messageable, _UserTag):
"""Represents a Discord member to a :class:`Guild`.
This implements a lot of the functionality of :class:`User`.
.. container:: operations
.. describe:: x == y
Checks if two members are equal.
Note that this works with :class:`User` instances too.
.. describe:: x != y
Checks if two members are not equal.
Note that this works with :class:`User` instances too.
.. describe:: hash(x)
Returns the member's hash.
.. describe:: str(x)
Returns the member's name with the discriminator.
Attributes
----------
joined_at: Optional[:class:`datetime.datetime`]
An aware datetime object that specifies the date and time in UTC that the member joined the guild.
If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be ``None``.
activities: Tuple[Union[:class:`BaseActivity`, :class:`Spotify`]]
The activities that the user is currently doing.
.. note::
Due to a Discord API limitation, a user's Spotify activity may not appear
if they are listening to a song with a title longer
than 128 characters. See :dpyissue:`1738` for more information.
guild: :class:`Guild`
The guild that the member belongs to.
nick: Optional[:class:`str`]
The guild specific nickname of the user.
pending: :class:`bool`
Whether the member is pending member verification.
.. versionadded:: 1.6
premium_since: Optional[:class:`datetime.datetime`]
An aware datetime object that specifies the date and time in UTC when the member used their
"Nitro boost" on the guild, if available. This could be ``None``.
"""
__slots__ = (
"_roles",
"joined_at",
"premium_since",
"activities",
"guild",
"pending",
"nick",
"_client_status",
"_user",
"_state",
"_avatar",
"_timeout",
"_flags",
)
if TYPE_CHECKING:
name: str
id: int
global_name: Optional[str]
discriminator: str
bot: bool
system: bool
created_at: datetime.datetime
default_avatar: Asset
avatar: Optional[Asset]
dm_channel: Optional[DMChannel]
create_dm = User.create_dm
mutual_guilds: List[Guild]
public_flags: PublicUserFlags
banner: Optional[Asset]
accent_color: Optional[Colour]
accent_colour: Optional[Colour]
def __init__(
self, *, data: MemberWithUserPayload, guild: Guild, state: ConnectionState
) -> None:
self._state: ConnectionState = state
self._user: User = state.store_user(data["user"])
self.guild: Guild = guild
self.joined_at: Optional[datetime.datetime] = utils.parse_time(data.get("joined_at"))
self.premium_since: Optional[datetime.datetime] = utils.parse_time(
data.get("premium_since")
)
self._roles: utils.SnowflakeList = utils.SnowflakeList(map(int, data["roles"]))
self._client_status: Dict[Optional[str], str] = {None: "offline"}
self.activities: Tuple[ActivityTypes, ...] = ()
self.nick: Optional[str] = data.get("nick", None)
self.pending: bool = data.get("pending", False)
self._avatar: Optional[str] = data.get("avatar")
self._timeout: Optional[datetime.datetime] = utils.parse_time(
data.get("communication_disabled_until")
)
self._flags: int = data.get("flags", 0)
def __str__(self) -> str:
return str(self._user)
def __repr__(self) -> str:
return (
f"<Member id={self._user.id} name={self._user.name!r} global_name={self._user.global_name!r}"
+ (f" discriminator={self._user.discriminator!r}" if self.discriminator != "0" else "")
+ f" bot={self._user.bot} nick={self.nick!r} guild={self.guild!r}>"
)
def __eq__(self, other: Any) -> bool:
return isinstance(other, _UserTag) and other.id == self.id
def __ne__(self, other: Any) -> bool:
return not self.__eq__(other)
def __hash__(self) -> int:
return hash(self._user)
def _from_message(cls, *, message: Message, data: MemberPayload) -> Self:
author = message.author
data["user"] = author._to_minimal_user_json() # type: ignore
return cls(data=data, guild=message.guild, state=message._state) # type: ignore
def _update_from_message(self, data: MemberPayload) -> None:
self.joined_at = utils.parse_time(data.get("joined_at"))
self.premium_since = utils.parse_time(data.get("premium_since"))
self._roles = utils.SnowflakeList(map(int, data["roles"]))
self.nick = data.get("nick", None)
self.pending = data.get("pending", False)
self._timeout = utils.parse_time(data.get("communication_disabled_until"))
self._flags = data.get("flags", 0)
def _try_upgrade(
cls, *, data: UserWithMemberPayload, guild: Guild, state: ConnectionState
) -> Union[User, Member]:
# A User object with a 'member' key
try:
member_data = data.pop("member")
except KeyError:
return state.create_user(data)
else:
member_data["user"] = data # type: ignore
return cls(data=member_data, guild=guild, state=state) # type: ignore
def _copy(cls, member: Self) -> Self:
self = cls.__new__(cls) # to bypass __init__
self._roles = utils.SnowflakeList(member._roles, is_sorted=True)
self.joined_at = member.joined_at
self.premium_since = member.premium_since
self._client_status = member._client_status.copy()
self.guild = member.guild
self.nick = member.nick
self.pending = member.pending
self.activities = member.activities
self._state = member._state
self._avatar = member._avatar
self._timeout = member._timeout
self._flags = member._flags
# Reference will not be copied unless necessary by PRESENCE_UPDATE
# See below
self._user = member._user
return self
async def _get_channel(self):
return await self.create_dm()
def _update(self, data: MemberPayload) -> None:
# the nickname change is optional,
# if it isn't in the payload then it didn't change
with contextlib.suppress(KeyError):
self.nick = data["nick"]
with contextlib.suppress(KeyError):
self.pending = data["pending"]
self.premium_since = utils.parse_time(data.get("premium_since"))
self._roles = utils.SnowflakeList(map(int, data["roles"]))
self._avatar = data.get("avatar")
self._timeout = utils.parse_time(data.get("communication_disabled_until"))
self._flags = data.get("flags", 0)
def _presence_update(
self, data: PartialPresenceUpdate, user: UserPayload
) -> Optional[Tuple[User, User]]:
self.activities = tuple((create_activity(self._state, x) for x in data["activities"]))
self._client_status = {
sys.intern(key): sys.intern(value) for key, value in data.get("client_status", {}).items() # type: ignore
}
self._client_status[None] = sys.intern(data["status"])
if len(user) > 1:
return self._update_inner_user(user)
return None
def _update_inner_user(self, user: UserPayload) -> Optional[Tuple[User, User]]:
u = self._user
original = (u.name, u._avatar, u.discriminator, u._public_flags)
# These keys seem to always be available
modified = (
user["username"],
user["avatar"],
user["discriminator"],
user.get("public_flags", 0),
)
if original != modified:
to_return = User._copy(self._user)
u.name, u._avatar, u.discriminator, u._public_flags = modified
# Signal to dispatch on_user_update
return to_return, u
return None
def status(self) -> Union[Status, str]:
"""Union[:class:`Status`, :class:`str`]: The member's overall status. If the value is unknown, then it will be a :class:`str` instead."""
return try_enum(Status, self._client_status[None])
def raw_status(self) -> str:
""":class:`str`: The member's overall status as a string value.
.. versionadded:: 1.5
"""
return self._client_status[None]
def status(self, value: Status) -> None:
# internal use only
self._client_status[None] = str(value)
def mobile_status(self) -> Status:
""":class:`Status`: The member's status on a mobile device, if applicable."""
return try_enum(Status, self._client_status.get("mobile", "offline"))
def desktop_status(self) -> Status:
""":class:`Status`: The member's status on the desktop client, if applicable."""
return try_enum(Status, self._client_status.get("desktop", "offline"))
def web_status(self) -> Status:
""":class:`Status`: The member's status on the web client, if applicable."""
return try_enum(Status, self._client_status.get("web", "offline"))
def is_on_mobile(self) -> bool:
""":class:`bool`: A helper function that determines if a member is active on a mobile device."""
return "mobile" in self._client_status
def colour(self) -> Colour:
""":class:`Colour`: A property that returns a colour denoting the rendered colour
for the member. If the default colour is the one rendered then an instance
of :meth:`Colour.default` is returned.
There is an alias for this named :attr:`color`.
"""
roles = self.roles[1:] # remove @everyone
# highest order of the colour is the one that gets rendered.
# if the highest is the default colour then the next one with a colour
# is chosen instead
for role in reversed(roles):
if role.colour.value:
return role.colour
return Colour.default()
def color(self) -> Colour:
""":class:`Colour`: A property that returns a color denoting the rendered color for
the member. If the default color is the one rendered then an instance of :meth:`Colour.default`
is returned.
There is an alias for this named :attr:`colour`.
"""
return self.colour
def roles(self) -> List[Role]:
"""List[:class:`Role`]: A :class:`list` of :class:`Role` that the member belongs to. Note
that the first element of this list is always the default '@everyone'
role.
These roles are sorted by their position in the role hierarchy.
"""
result = []
g = self.guild
for role_id in self._roles:
role = g.get_role(role_id)
if role:
result.append(role)
result.append(g.default_role)
result.sort()
return result
def mention(self) -> str:
""":class:`str`: Returns a string that allows you to mention the member.
.. versionchanged:: 2.2
The nickname mention syntax is no longer returned as it is deprecated by Discord.
"""
return f"<@{self._user.id}>"
def display_name(self) -> str:
""":class:`str`: Returns the user's display name.
For regular users this is just their username, but
if they have a guild specific nickname then that
is returned instead.
"""
return self.nick or self.name
def display_avatar(self) -> Asset:
""":class:`Asset`: Returns the member's display avatar.
For regular members this is just their avatar, but
if they have a guild specific avatar then that
is returned instead.
.. versionadded:: 2.0
"""
return self.guild_avatar or self._user.avatar or self._user.default_avatar
def guild_avatar(self) -> Optional[Asset]:
"""Optional[:class:`Asset`]: Returns an :class:`Asset` for the guild avatar
the member has. If unavailable, ``None`` is returned.
.. versionadded:: 2.0
"""
if self._avatar is None:
return None
return Asset._from_guild_avatar(self._state, self.guild.id, self.id, self._avatar)
def activity(self) -> Optional[ActivityTypes]:
"""Optional[Union[:class:`BaseActivity`, :class:`Spotify`]]: Returns the primary
activity the user is currently doing. Could be ``None`` if no activity is being done.
.. note::
Due to a Discord API limitation, this may be ``None`` if
the user is listening to a song on Spotify with a title longer
than 128 characters. See :dpyissue:`1738` for more information.
.. note::
A user may have multiple activities, these can be accessed under :attr:`activities`.
"""
if self.activities:
return self.activities[0]
return None
def flags(self) -> MemberFlags:
""":class:`MemberFlags`: Returns the member's flags.
.. versionadded:: 2.6
"""
return MemberFlags._from_value(self._flags)
def mentioned_in(self, message: Message) -> bool:
"""Checks if the member is mentioned in the specified message.
Parameters
----------
message: :class:`Message`
The message to check if you're mentioned in.
Returns
-------
:class:`bool`
Indicates if the member is mentioned in the message.
"""
if message.guild is None or message.guild.id != self.guild.id:
return False
if self._user.mentioned_in(message):
return True
return any(self._roles.has(role.id) for role in message.role_mentions)
def top_role(self) -> Role:
""":class:`Role`: Returns the member's highest role.
This is useful for figuring where a member stands in the role
hierarchy chain.
"""
guild = self.guild
if len(self._roles) == 0:
return guild.default_role
return max(guild.get_role(rid) or guild.default_role for rid in self._roles)
def guild_permissions(self) -> Permissions:
""":class:`Permissions`: Returns the member's guild permissions.
This only takes into consideration the guild permissions
and not most of the implied permissions or any of the
channel permission overwrites. For 100% accurate permission
calculation, please use :meth:`abc.GuildChannel.permissions_for`.
This does take into consideration guild ownership and the
administrator implication.
"""
if self.guild.owner_id == self.id:
return Permissions.all()
base = Permissions.none()
for r in self.roles:
base.value |= r.permissions.value
if base.administrator:
return Permissions.all()
return base
def voice(self) -> Optional[VoiceState]:
"""Optional[:class:`VoiceState`]: Returns the member's current voice state."""
return self.guild._voice_state_for(self._user.id)
def communication_disabled_until(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: A datetime object that represents
the time in which the member will be able to interact again.
.. note::
This is ``None`` if the user has no timeout.
.. versionadded:: 2.0
"""
if self._timeout is None or self._timeout < utils.utcnow():
return None
return self._timeout
async def ban(
self,
*,
delete_message_seconds: Optional[int] = None,
delete_message_days: Optional[Literal[0, 1, 2, 3, 4, 5, 6, 7]] = None,
reason: Optional[str] = None,
) -> None:
"""|coro|
Bans this member. Equivalent to :meth:`Guild.ban`.
"""
await self.guild.ban(
self,
reason=reason,
delete_message_seconds=delete_message_seconds,
delete_message_days=delete_message_days,
)
async def unban(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Unbans this member. Equivalent to :meth:`Guild.unban`.
"""
await self.guild.unban(self, reason=reason)
async def kick(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Kicks this member. Equivalent to :meth:`Guild.kick`.
"""
await self.guild.kick(self, reason=reason)
async def timeout(
self,
timeout: Union[datetime.datetime, datetime.timedelta],
*,
reason: Optional[str] = None,
) -> None:
"""|coro|
Times out this member.
.. note::
This is a more direct method of timing out a member.
You can also time out members using :meth:`Member.edit`.
.. versionadded:: 2.0
Parameters
----------
timeout: Optional[Union[:class:`~datetime.datetime`, :class:`~datetime.timedelta`]]
The time until the member should not be timed out.
Set this to None to disable their timeout.
reason: Optional[:class:`str`]
The reason for editing this member. Shows up on the audit log.
"""
await self.edit(timeout=timeout, reason=reason)
async def edit(
self,
*,
nick: Optional[str] = MISSING,
mute: bool = MISSING,
deafen: bool = MISSING,
suppress: bool = MISSING,
roles: List[abc.Snowflake] = MISSING,
voice_channel: Optional[VocalGuildChannel] = MISSING,
reason: Optional[str] = None,
timeout: Optional[Union[datetime.datetime, datetime.timedelta]] = MISSING,
flags: MemberFlags = MISSING,
bypass_verification: bool = MISSING,
) -> Optional[Member]:
"""|coro|
Edits the member's data.
Depending on the parameter passed, this requires different permissions listed below:
+---------------------+--------------------------------------+
| Parameter | Permission |
+---------------------+--------------------------------------+
| nick | :attr:`Permissions.manage_nicknames` |
+---------------------+--------------------------------------+
| mute | :attr:`Permissions.mute_members` |
+---------------------+--------------------------------------+
| deafen | :attr:`Permissions.deafen_members` |
+---------------------+--------------------------------------+
| roles | :attr:`Permissions.manage_roles` |
+---------------------+--------------------------------------+
| voice_channel | :attr:`Permissions.move_members` |
+---------------------+--------------------------------------+
| timeout | :attr:`Permissions.moderate_members` |
+---------------------+--------------------------------------+
| bypass_verification | :attr:`Permissions.moderate_members` |
+---------------------+--------------------------------------+
All parameters are optional.
.. versionchanged:: 1.1
Can now pass ``None`` to ``voice_channel`` to kick a member from voice.
.. versionchanged:: 2.0
The newly member is now optionally returned, if applicable.
Parameters
----------
nick: Optional[:class:`str`]
The member's new nickname. Use ``None`` to remove the nickname.
mute: :class:`bool`
Indicates if the member should be guild muted or un-muted.
deafen: :class:`bool`
Indicates if the member should be guild deafened or un-deafened.
suppress: :class:`bool`
Indicates if the member should be suppressed in stage channels.
.. versionadded:: 1.7
roles: List[:class:`Role`]
The member's new list of roles. This *replaces* the roles.
voice_channel: Optional[:class:`VoiceChannel`]
The voice channel to move the member to.
Pass ``None`` to kick them from voice.
reason: Optional[:class:`str`]
The reason for editing this member. Shows up on the audit log.
timeout: Optional[Union[:class:`~datetime.datetime`, :class:`~datetime.timedelta`]
The time until the member should not be timed out.
Set this to None to disable their timeout.
.. versionadded:: 2.0
flags: :class:`~nextcord.MemberFlags`
The flags to set for this member.
Currently only :class:`~nextcord.MemberFlags.bypasses_verification` is able to be set.
.. versionadded:: 2.6
bypass_verification: :class:`bool`
Indicates if the member should be allowed to bypass the guild verification requirements.
.. versionadded:: 2.6
Raises
------
Forbidden
You do not have the proper permissions to the action requested.
HTTPException
The operation failed.
Returns
-------
Optional[:class:`.Member`]
The newly updated member, if applicable. This is only returned
when certain fields are updated.
"""
http = self._state.http
guild_id = self.guild.id
me = self._state.self_id == self.id
payload: Dict[str, Any] = {}
if nick is not MISSING:
nick = nick or ""
if me:
await http.change_my_nickname(guild_id, nick, reason=reason)
else:
payload["nick"] = nick
if deafen is not MISSING:
payload["deaf"] = deafen
if mute is not MISSING:
payload["mute"] = mute
if suppress is not MISSING:
if self.voice is None:
raise TypeError(
"You can only suppress members which are connected to a voice channel"
)
voice_state_payload = {
"channel_id": self.voice.channel.id, # type: ignore # id should exist
"suppress": suppress,
}
if suppress or self.bot:
voice_state_payload["request_to_speak_timestamp"] = None
if me:
await http.edit_my_voice_state(guild_id, voice_state_payload)
else:
if not suppress:
voice_state_payload["request_to_speak_timestamp"] = utils.utcnow().isoformat()
await http.edit_voice_state(guild_id, self.id, voice_state_payload)
if voice_channel is not MISSING:
payload["channel_id"] = voice_channel and voice_channel.id
if roles is not MISSING:
payload["roles"] = tuple(r.id for r in roles)
if isinstance(timeout, datetime.timedelta):
payload["communication_disabled_until"] = (utils.utcnow() + timeout).isoformat()
elif isinstance(timeout, datetime.datetime):
payload["communication_disabled_until"] = timeout.isoformat()
elif timeout is None:
payload["communication_disabled_until"] = None
elif timeout is MISSING:
pass
else:
raise TypeError(
"Timeout must be a `datetime.datetime` or `datetime.timedelta`"
f"not {timeout.__class__.__name__}"
)
if flags is MISSING:
flags = MemberFlags()
if bypass_verification is not MISSING:
flags.bypasses_verification = bypass_verification
if flags.value != 0:
payload["flags"] = flags.value
if payload:
data = await http.edit_member(guild_id, self.id, reason=reason, **payload)
return Member(data=data, guild=self.guild, state=self._state)
return None
async def request_to_speak(self) -> None:
"""|coro|
Request to speak in the connected channel.
Only applies to stage channels.
.. note::
Requesting members that are not the client is equivalent
to :attr:`.edit` providing ``suppress`` as ``False``.
.. versionadded:: 1.7
Raises
------
Forbidden
You do not have the proper permissions to the action requested.
HTTPException
The operation failed.
"""
payload = {
"channel_id": self.voice.channel.id, # type: ignore # should exist
"request_to_speak_timestamp": utils.utcnow().isoformat(),
}
if self._state.self_id != self.id:
payload["suppress"] = False
await self._state.http.edit_voice_state(self.guild.id, self.id, payload)
else:
await self._state.http.edit_my_voice_state(self.guild.id, payload)
async def move_to(
self, channel: Optional[VocalGuildChannel], *, reason: Optional[str] = None
) -> None:
"""|coro|
Moves a member to a new voice channel (they must be connected first).
You must have the :attr:`~Permissions.move_members` permission to
use this.
This raises the same exceptions as :meth:`edit`.
.. versionchanged:: 1.1
Can now pass ``None`` to kick a member from voice.
Parameters
----------
channel: Optional[:class:`VoiceChannel`]
The new voice channel to move the member to.
Pass ``None`` to kick them from voice.
reason: Optional[:class:`str`]
The reason for doing this action. Shows up on the audit log.
"""
await self.edit(voice_channel=channel, reason=reason)
async def disconnect(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Disconnects a member from the voice channel they are connected to.
You must have the :attr:`~Permissions.move_members` permission to
use this.
This raises the same exceptions as :meth:`edit`.
Parameters
----------
reason: Optional[:class:`str`]
The reason for doing this action. Shows up on the audit log.
"""
await self.edit(voice_channel=None, reason=reason)
async def add_roles(
self, *roles: Snowflake, reason: Optional[str] = None, atomic: bool = True
) -> None:
r"""|coro|
Gives the member a number of :class:`Role`\s.
You must have the :attr:`~Permissions.manage_roles` permission to
use this, and the added :class:`Role`\s must appear lower in the list
of roles than the highest role of the member.
Parameters
----------
\*roles: :class:`abc.Snowflake`
An argument list of :class:`abc.Snowflake` representing a :class:`Role`
to give to the member.
reason: Optional[:class:`str`]
The reason for adding these roles. Shows up on the audit log.
atomic: :class:`bool`
Whether to atomically add roles. This will ensure that multiple
operations will always be applied regardless of the current
state of the cache.
Raises
------
Forbidden
You do not have permissions to add these roles.
HTTPException
Adding roles failed.
"""
if not atomic:
new_roles: list[Snowflake] = utils.unique(
Object(id=r.id) for s in (self.roles[1:], roles) for r in s
)
await self.edit(roles=new_roles, reason=reason)
else:
req = self._state.http.add_role
guild_id = self.guild.id
user_id = self.id
for role in roles:
await req(guild_id, user_id, role.id, reason=reason)
async def remove_roles(
self, *roles: Snowflake, reason: Optional[str] = None, atomic: bool = True
) -> None:
r"""|coro|
Removes :class:`Role`\s from this member.
You must have the :attr:`~Permissions.manage_roles` permission to
use this, and the removed :class:`Role`\s must appear lower in the list
of roles than the highest role of the member.
Parameters
----------
\*roles: :class:`abc.Snowflake`
An argument list of :class:`abc.Snowflake` representing a :class:`Role`
to remove from the member.
reason: Optional[:class:`str`]
The reason for removing these roles. Shows up on the audit log.
atomic: :class:`bool`
Whether to atomically remove roles. This will ensure that multiple
operations will always be applied regardless of the current
state of the cache.
Raises
------
Forbidden
You do not have permissions to remove these roles.
HTTPException
Removing the roles failed.
"""
if not atomic:
new_roles: list[Snowflake] = [
Object(id=r.id) for r in self.roles[1:]
] # remove @everyone
for role in roles:
with contextlib.suppress(ValueError):
new_roles.remove(Object(id=role.id))
await self.edit(roles=new_roles, reason=reason)
else:
req = self._state.http.remove_role
guild_id = self.guild.id
user_id = self.id
for role in roles:
await req(guild_id, user_id, role.id, reason=reason)
def get_role(self, role_id: int, /) -> Optional[Role]:
"""Returns a role with the given ID from roles which the member has.
.. versionadded:: 2.0
Parameters
----------
role_id: :class:`int`
The ID to search for.
Returns
-------
Optional[:class:`Role`]
The role or ``None`` if not found in the member's roles.
"""
return self.guild.get_role(role_id) if self._roles.has(role_id) else None
Snowflake = Union[str, int]
class User(BaseUser, abc.Messageable):
"""Represents a Discord user.
.. container:: operations
.. describe:: x == y
Checks if two users are equal.
.. describe:: x != y
Checks if two users are not equal.
.. describe:: hash(x)
Return the user's hash.
.. describe:: str(x)
Returns the user's name with discriminator.
Attributes
----------
name: :class:`str`
The user's username.
id: :class:`int`
The user's unique ID.
global_name: Optional[:class:`str`]
The user's default name, if any.
..versionadded: 2.6
discriminator: :class:`str`
The user's discriminator.
.. warning::
This field is deprecated, and will only return if the user has not yet migrated to the
new `username <https://dis.gd/usernames>`_ update.
.. deprecated:: 2.6
bot: :class:`bool`
Specifies if the user is a bot account.
system: :class:`bool`
Specifies if the user is a system user (i.e. represents Discord officially).
"""
__slots__ = ("_stored",)
def __init__(
self, *, state: ConnectionState, data: Union[PartialUserPayload, UserPayload]
) -> None:
super().__init__(state=state, data=data)
self._stored: bool = False
def __repr__(self) -> str:
return (
f"<User id={self.id} name={self.name!r} global_name={self.global_name!r}"
+ (f" discriminator={self.discriminator!r}" if self.discriminator != "0" else "")
+ f" bot={self.bot}>"
)
def __del__(self) -> None:
try:
if self._stored:
self._state.deref_user(self.id)
except Exception:
pass
def _copy(cls, user: User):
self = super()._copy(user)
self._stored = False
return self
async def _get_channel(self) -> DMChannel:
return await self.create_dm()
def dm_channel(self) -> Optional[DMChannel]:
"""Optional[:class:`DMChannel`]: Returns the channel associated with this user if it exists.
If this returns ``None``, you can create a DM channel by calling the
:meth:`create_dm` coroutine function.
"""
return self._state._get_private_channel_by_user(self.id)
def mutual_guilds(self) -> List[Guild]:
"""List[:class:`Guild`]: The guilds that the user shares with the client.
.. note::
This will only return mutual guilds within the client's internal cache.
.. versionadded:: 1.7
"""
return [guild for guild in self._state._guilds.values() if guild.get_member(self.id)]
async def create_dm(self) -> DMChannel:
"""|coro|
Creates a :class:`DMChannel` with this user.
This should be rarely called, as this is done transparently for most
people.
Returns
-------
:class:`.DMChannel`
The channel that was created.
"""
found = self.dm_channel
if found is not None:
return found
state = self._state
data: DMChannelPayload = await state.http.start_private_message(self.id)
return state.add_dm_channel(data)
def _transform_member_id(
entry: AuditLogEntry, data: Optional[Snowflake]
) -> Union[Member, User, None]:
if data is None:
return None
return entry._get_member(int(data)) | null |
161,002 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
r"""Represents an Audit Log entry.
You retrieve these via :meth:`Guild.audit_logs`.
.. container:: operations
.. describe:: x == y
Checks if two entries are equal.
.. describe:: x != y
Checks if two entries are not equal.
.. describe:: hash(x)
Returns the entry's hash.
.. versionchanged:: 1.7
Audit log entries are now comparable and hashable.
Attributes
----------
action: :class:`AuditLogAction`
The action that was done.
user: :class:`abc.User`
The user who initiated this action. Usually a :class:`Member`\, unless gone
then it's a :class:`User`.
id: :class:`int`
The entry ID.
target: Any
The target that got changed. The exact type of this depends on
the action being done.
reason: Optional[:class:`str`]
The reason this action was done.
extra: Any
Extra information that this entry has that might be useful.
For most actions, this is ``None``. However in some cases it
contains extra information. See :class:`AuditLogAction` for
which actions have this field filled out.
"""
extra: Union[
_AuditLogProxyMemberPrune,
_AuditLogProxyMemberMoveOrMessageDelete,
_AuditLogProxyMemberDisconnect,
_AuditLogProxyPinAction,
_AuditLogProxyStageInstanceAction,
_AuditLogProxyAutoModerationBlockMessage,
Member,
User,
None,
Role,
]
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
self._state = guild._state
self.guild = guild
self._auto_moderation_rules = auto_moderation_rules
self._users = users
self._from_data(data)
def _from_data(self, data: AuditLogEntryPayload) -> None:
self.action = enums.try_enum(enums.AuditLogAction, data["action_type"])
self.id = int(data["id"])
# this key is technically not usually present
self.reason = data.get("reason")
self.extra = data.get("options", {}) # type: ignore
# I gave up trying to fix this
elems: Dict[str, Any] = {}
channel_id = int(self.extra["channel_id"]) if self.extra.get("channel_id", None) else None
if isinstance(self.action, enums.AuditLogAction) and self.extra:
if self.action is enums.AuditLogAction.member_prune:
# member prune has two keys with useful information
self.extra = type( # type: ignore
"_AuditLogProxy", (), {k: int(v) for k, v in self.extra.items()} # type: ignore
)()
elif (
self.action is enums.AuditLogAction.member_move
or self.action is enums.AuditLogAction.message_delete
):
elems = {
"count": int(self.extra["count"]),
}
elif self.action is enums.AuditLogAction.member_disconnect:
# The member disconnect action has a dict with some information
elems = {
"count": int(self.extra["count"]),
}
elif self.action.name.endswith("pin"):
# the pin actions have a dict with some information
elems = {
"message_id": int(self.extra["message_id"]),
}
elif self.action.name.startswith("overwrite_"):
# the overwrite_ actions have a dict with some information
instance_id = int(self.extra["id"])
the_type = self.extra.get("type")
if the_type == "1":
self.extra = self._get_member(instance_id)
elif the_type == "0":
role = self.guild.get_role(instance_id)
if role is None:
role = Object(id=instance_id)
role.name = self.extra.get("role_name") # type: ignore
self.extra = role # type: ignore
elif self.action.name.startswith("stage_instance"):
channel_id = int(self.extra["channel_id"])
elems = {"channel": self.guild.get_channel(channel_id) or Object(id=channel_id)}
elif (
self.action is enums.AuditLogAction.auto_moderation_block_message
or self.action is enums.AuditLogAction.auto_moderation_flag_to_channel
or self.action is enums.AuditLogAction.auto_moderation_user_communication_disabled
):
elems = {
"rule_name": self.extra["auto_moderation_rule_name"],
"rule_trigger_type": enums.try_enum(
enums.AutoModerationTriggerType,
int(self.extra["auto_moderation_rule_trigger_type"]),
),
}
# this just gets automatically filled in if present, this way prevents crashes if channel_id is None
if channel_id and self.action:
elems["channel"] = self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id)
if type(self.extra) is dict:
self.extra = type("_AuditLogProxy", (), elems)() # type: ignore
# this key is not present when the above is present, typically.
# It's a list of { new_value: a, old_value: b, key: c }
# where new_value and old_value are not guaranteed to be there depending
# on the action type, so let's just fetch it for now and only turn it
# into meaningful data when requested
self._changes = data.get("changes", [])
self.user = self._get_member(utils.get_as_snowflake(data, "user_id")) # type: ignore
self._target_id = utils.get_as_snowflake(data, "target_id")
def _get_member(self, user_id: int) -> Union[Member, User, None]:
return self.guild.get_member(user_id) or self._users.get(user_id)
def __repr__(self) -> str:
return f"<AuditLogEntry id={self.id} action={self.action} user={self.user!r}>"
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the entry's creation time in UTC."""
return utils.snowflake_time(self.id)
def target(self) -> AuditTarget:
try:
converter = getattr(self, "_convert_target_" + str(self.action.target_type))
except AttributeError:
if self._target_id is None:
return None
return Object(id=self._target_id)
else:
return converter(self._target_id)
def category(self) -> Optional[enums.AuditLogActionCategory]:
"""Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable."""
return self.action.category
def changes(self) -> AuditLogChanges:
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj
def before(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's prior state."""
return self.changes.before
def after(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's subsequent state."""
return self.changes.after
def _convert_target_guild(self, target_id: int) -> Guild:
return self.guild
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
return self.guild.get_channel(target_id) or Object(id=target_id)
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
return self.guild.get_role(target_id) or Object(id=target_id)
def _convert_target_invite(self, target_id: int) -> Invite:
# invites have target_id set to null
# so figure out which change has the full invite data
changeset = self.before if self.action is enums.AuditLogAction.invite_delete else self.after
fake_payload = {
"max_age": changeset.max_age,
"max_uses": changeset.max_uses,
"code": changeset.code,
"temporary": changeset.temporary,
"uses": changeset.uses,
}
obj = Invite(state=self._state, data=fake_payload, guild=self.guild, channel=changeset.channel) # type: ignore
with contextlib.suppress(AttributeError):
obj.inviter = changeset.inviter
return obj
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
return self._state.get_emoji(target_id) or Object(id=target_id)
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
return self.guild.get_stage_instance(target_id) or Object(id=target_id)
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
return self._state.get_sticker(target_id) or Object(id=target_id)
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
return self.guild.get_thread(target_id) or Object(id=target_id)
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
return self._auto_moderation_rules.get(rule_id) or Object(id=rule_id)
class Guild(Hashable):
"""Represents a Discord guild.
This is referred to as a "server" in the official Discord UI.
.. container:: operations
.. describe:: x == y
Checks if two guilds are equal.
.. describe:: x != y
Checks if two guilds are not equal.
.. describe:: hash(x)
Returns the guild's hash.
.. describe:: str(x)
Returns the guild's name.
Attributes
----------
name: :class:`str`
The guild name.
emojis: Tuple[:class:`Emoji`, ...]
All emojis that the guild owns.
stickers: Tuple[:class:`GuildSticker`, ...]
All stickers that the guild owns.
.. versionadded:: 2.0
region: :class:`VoiceRegion`
The region the guild belongs on. There is a chance that the region
will be a :class:`str` if the value is not recognised by the enumerator.
afk_timeout: :class:`int`
The timeout to get sent to the AFK channel.
afk_channel: Optional[:class:`VoiceChannel`]
The channel that denotes the AFK channel. ``None`` if it doesn't exist.
id: :class:`int`
The guild's ID.
owner_id: :class:`int`
The guild owner's ID. Use :attr:`Guild.owner` instead.
unavailable: :class:`bool`
Indicates if the guild is unavailable. If this is ``True`` then the
reliability of other attributes outside of :attr:`Guild.id` is slim and they might
all be ``None``. It is best to not do anything with the guild if it is unavailable.
Check the :func:`on_guild_unavailable` and :func:`on_guild_available` events.
max_presences: Optional[:class:`int`]
The maximum amount of presences for the guild.
max_members: Optional[:class:`int`]
The maximum amount of members for the guild.
.. note::
This attribute is only available via :meth:`.Client.fetch_guild`.
max_video_channel_users: Optional[:class:`int`]
The maximum amount of users in a video channel.
.. versionadded:: 1.4
description: Optional[:class:`str`]
The guild's description.
mfa_level: :class:`int`
Indicates the guild's two factor authorisation level. If this value is 0 then
the guild does not require 2FA for their administrative members. If the value is
1 then they do.
verification_level: :class:`VerificationLevel`
The guild's verification level.
explicit_content_filter: :class:`ContentFilter`
The guild's explicit content filter.
default_notifications: :class:`NotificationLevel`
The guild's notification settings.
features: List[:class:`str`]
A list of features that the guild has. The features that a guild can have are
subject to arbitrary change by Discord.
They are currently as follows:
- ``ANIMATED_BANNER``: Guild can upload an animated banner.
- ``ANIMATED_ICON``: Guild can upload an animated icon.
- ``AUTO_MODERATION``: Guild has set up auto moderation rules.
- ``APPLICATION_COMMAND_PERMISSIONS_V2``: Guild is using the old permissions configuration behavior.
- ``BANNER``: Guild can upload and use a banner. (i.e. :attr:`.banner`)
- ``COMMUNITY``: Guild is a community server.
- ``DEVELOPER_SUPPORT_SERVER``: Guild has been set as a support server on the App Directory.
- ``DISCOVERABLE``: Guild shows up in Server Discovery.
- ``FEATURABLE``: Guild is able to be featured in Server Discovery.
- ``INVITES_DISABLED``: Guild has paused invites, preventing new users from joining.
- ``INVITE_SPLASH``: Guild's invite page can have a special splash.
- ``MEMBER_VERIFICATION_GATE_ENABLED``: Guild has Membership Screening enabled.
- ``MONETIZATION_ENABLED``: Guild has enabled monetization.
- ``MORE_STICKERS``: Guild has increased custom sticker slots.
- ``NEWS``: Guild can create news channels.
- ``PARTNERED``: Guild is a partnered server.
- ``PREVIEW_ENABLED``: Guild can be viewed before being accepted via Membership Screening.
- ``RAID_ALERTS_DISABLED``: Guild disabled alerts for join raids in the configured safety alerts channel.
- ``ROLE_ICONS``: Guild is able to set role icons.
- ``TICKETED_EVENTS_ENABLED``: Guild has enabled ticketed events.
- ``VANITY_URL``: Guild can have a vanity invite URL (e.g. discord.gg/discord-api).
- ``VERIFIED``: Guild is a verified server.
- ``VIP_REGIONS``: Guild has VIP voice regions.
- ``WELCOME_SCREEN_ENABLED``: Guild has enabled the welcome screen.
premium_tier: :class:`int`
The premium tier for this guild. Corresponds to "Boost Level" in the official UI.
The number goes from 0 to 3 inclusive.
premium_subscription_count: :class:`int`
The number of "boosts" this guild currently has.
preferred_locale: Optional[:class:`str`]
The preferred locale for the guild. Used when filtering Server Discovery
results to a specific language.
nsfw_level: :class:`NSFWLevel`
The guild's NSFW level.
.. versionadded:: 2.0
approximate_member_count: Optional[:class:`int`]
The approximate number of members in the guild. This is ``None`` unless the guild is obtained
using :meth:`Client.fetch_guild` with ``with_counts=True``.
.. versionadded:: 2.0
approximate_presence_count: Optional[:class:`int`]
The approximate number of members currently active in the guild.
This includes idle, dnd, online, and invisible members. Offline members are excluded.
This is ``None`` unless the guild is obtained using :meth:`Client.fetch_guild`
with ``with_counts=True``.
.. versionadded:: 2.0
max_stage_video_channel_users: Optional[:class:`int`]
The maximum amount of users in a stage channel when video is being broadcasted.
.. versionadded:: 2.6
"""
__slots__ = (
"afk_timeout",
"afk_channel",
"name",
"id",
"unavailable",
"region",
"owner_id",
"mfa_level",
"emojis",
"stickers",
"features",
"verification_level",
"explicit_content_filter",
"default_notifications",
"description",
"max_presences",
"max_members",
"max_video_channel_users",
"premium_tier",
"premium_subscription_count",
"preferred_locale",
"nsfw_level",
"_application_commands",
"_members",
"_channels",
"_icon",
"_banner",
"_state",
"_roles",
"_member_count",
"_large",
"_splash",
"_voice_states",
"_system_channel_id",
"_system_channel_flags",
"_discovery_splash",
"_rules_channel_id",
"_public_updates_channel_id",
"_stage_instances",
"_threads",
"_scheduled_events",
"approximate_member_count",
"approximate_presence_count",
"_premium_progress_bar_enabled",
"_safety_alerts_channel_id",
"max_stage_video_channel_users",
)
_PREMIUM_GUILD_LIMITS: ClassVar[Dict[Optional[int], _GuildLimit]] = {
None: _GuildLimit(emoji=50, stickers=5, bitrate=96e3, filesize=25 * 1024 * 1024),
0: _GuildLimit(emoji=50, stickers=5, bitrate=96e3, filesize=25 * 1024 * 1024),
1: _GuildLimit(emoji=100, stickers=15, bitrate=128e3, filesize=25 * 1024 * 1024),
2: _GuildLimit(emoji=150, stickers=30, bitrate=256e3, filesize=50 * 1024 * 1024),
3: _GuildLimit(emoji=250, stickers=60, bitrate=384e3, filesize=100 * 1024 * 1024),
}
def __init__(self, *, data: GuildPayload, state: ConnectionState) -> None:
self._channels: Dict[int, GuildChannel] = {}
self._members: Dict[int, Member] = {}
self._scheduled_events: Dict[int, ScheduledEvent] = {}
self._voice_states: Dict[int, VoiceState] = {}
self._threads: Dict[int, Thread] = {}
self._application_commands: Dict[int, BaseApplicationCommand] = {}
self._state: ConnectionState = state
self._from_data(data)
def _add_channel(self, channel: GuildChannel, /) -> None:
self._channels[channel.id] = channel
def _remove_channel(self, channel: Snowflake, /) -> None:
self._channels.pop(channel.id, None)
def _voice_state_for(self, user_id: int, /) -> Optional[VoiceState]:
return self._voice_states.get(user_id)
def _add_member(self, member: Member, /) -> None:
self._members[member.id] = member
def _store_thread(self, payload: ThreadPayload, /) -> Thread:
thread = Thread(guild=self, state=self._state, data=payload)
self._threads[thread.id] = thread
return thread
def _remove_member(self, member: Snowflake, /) -> None:
self._members.pop(member.id, None)
def _add_thread(self, thread: Thread, /) -> None:
self._threads[thread.id] = thread
def _remove_thread(self, thread: Snowflake, /) -> None:
self._threads.pop(thread.id, None)
def _clear_threads(self) -> None:
self._threads.clear()
def _remove_threads_by_channel(self, channel_id: int) -> None:
to_remove = [k for k, t in self._threads.items() if t.parent_id == channel_id]
for k in to_remove:
del self._threads[k]
def _filter_threads(self, channel_ids: Set[int]) -> Dict[int, Thread]:
to_remove: Dict[int, Thread] = {
k: t for k, t in self._threads.items() if t.parent_id in channel_ids
}
for k in to_remove:
del self._threads[k]
return to_remove
def _add_scheduled_event(self, event: ScheduledEvent) -> None:
self._scheduled_events[event.id] = event
def _remove_scheduled_event(self, event: int) -> None:
self._scheduled_events.pop(event, None)
def _store_scheduled_event(self, payload: ScheduledEventPayload) -> ScheduledEvent:
event = ScheduledEvent(guild=self, state=self._state, data=payload)
self._scheduled_events[event.id] = event
return event
def __str__(self) -> str:
return self.name or ""
def __repr__(self) -> str:
attrs = (
("id", self.id),
("name", self.name),
("shard_id", self.shard_id),
("chunked", self.chunked),
("member_count", getattr(self, "_member_count", None)),
)
inner = " ".join("%s=%r" % t for t in attrs)
return f"<Guild {inner}>"
def _update_voice_state(
self, data: GuildVoiceState, channel_id: int
) -> Tuple[Optional[Member], VoiceState, VoiceState]:
user_id = int(data["user_id"])
channel = self.get_channel(channel_id)
try:
# check if we should remove the voice state from cache
if channel is None:
after = self._voice_states.pop(user_id)
else:
after = self._voice_states[user_id]
before = copy.copy(after)
after._update(data, channel) # type: ignore
except KeyError:
# if we're here then we're getting added into the cache
after = VoiceState(data=data, channel=channel) # type: ignore
before = VoiceState(data=data, channel=None) # type: ignore
self._voice_states[user_id] = after
member = self.get_member(user_id)
if member is None:
try:
member = Member(data=data["member"], state=self._state, guild=self)
except KeyError:
member = None
return member, before, after
def _add_role(self, role: Role, /) -> None:
# roles get added to the bottom (position 1, pos 0 is @everyone)
# so since self.roles has the @everyone role, we can't increment
# its position because it's stuck at position 0. Luckily x += False
# is equivalent to adding 0. So we cast the position to a bool and
# increment it.
for r in self._roles.values():
r.position += not r.is_default()
self._roles[role.id] = role
def _remove_role(self, role_id: int, /) -> Role:
# this raises KeyError if it fails..
role = self._roles.pop(role_id)
# since it didn't, we can change the positions now
# basically the same as above except we only decrement
# the position if we're above the role we deleted.
for r in self._roles.values():
r.position -= r.position > role.position
return role
def _from_data(self, guild: GuildPayload) -> None:
# according to Stan, this is always available even if the guild is unavailable
# I don't have this guarantee when someone updates the guild.
member_count = guild.get("member_count", None)
if member_count is not None:
self._member_count: int = member_count
self.name: str = guild.get("name")
self.region: VoiceRegion = try_enum(VoiceRegion, guild.get("region"))
self.verification_level: VerificationLevel = try_enum(
VerificationLevel, guild.get("verification_level")
)
self.default_notifications: NotificationLevel = try_enum(
NotificationLevel, guild.get("default_message_notifications")
)
self.explicit_content_filter: ContentFilter = try_enum(
ContentFilter, guild.get("explicit_content_filter", 0)
)
self.afk_timeout: int = guild.get("afk_timeout")
self._icon: Optional[str] = guild.get("icon")
self._banner: Optional[str] = guild.get("banner")
self.unavailable: bool = guild.get("unavailable", False)
self.id: int = int(guild["id"])
self._roles: Dict[int, Role] = {}
state = self._state # speed up attribute access
for r in guild.get("roles", []):
role = Role(guild=self, data=r, state=state)
self._roles[role.id] = role
self.mfa_level: MFALevel = guild.get("mfa_level")
self.emojis: Tuple[Emoji, ...] = tuple(
(state.store_emoji(self, d) for d in guild.get("emojis", []))
)
self.stickers: Tuple[GuildSticker, ...] = tuple(
(state.store_sticker(self, d) for d in guild.get("stickers", []))
)
self.features: List[GuildFeature] = guild.get("features", [])
self._splash: Optional[str] = guild.get("splash")
self._system_channel_id: Optional[int] = utils.get_as_snowflake(guild, "system_channel_id")
self.description: Optional[str] = guild.get("description")
self.max_presences: Optional[int] = guild.get("max_presences")
self.max_members: Optional[int] = guild.get("max_members")
self.max_video_channel_users: Optional[int] = guild.get("max_video_channel_users")
self.max_stage_video_channel_users: Optional[int] = guild.get(
"max_stage_video_channel_users"
)
self.premium_tier: int = guild.get("premium_tier", 0)
self.premium_subscription_count: int = guild.get("premium_subscription_count") or 0
self._system_channel_flags: int = guild.get("system_channel_flags", 0)
self.preferred_locale: Optional[str] = guild.get("preferred_locale")
self._discovery_splash: Optional[str] = guild.get("discovery_splash")
self._rules_channel_id: Optional[int] = utils.get_as_snowflake(guild, "rules_channel_id")
self._public_updates_channel_id: Optional[int] = utils.get_as_snowflake(
guild, "public_updates_channel_id"
)
self.nsfw_level: NSFWLevel = try_enum(NSFWLevel, guild.get("nsfw_level", 0))
self.approximate_presence_count = guild.get("approximate_presence_count")
self.approximate_member_count = guild.get("approximate_member_count")
self._stage_instances: Dict[int, StageInstance] = {}
for s in guild.get("stage_instances", []):
stage_instance = StageInstance(guild=self, data=s, state=state)
self._stage_instances[stage_instance.id] = stage_instance
cache_joined = self._state.member_cache_flags.joined
self_id = self._state.self_id
for mdata in guild.get("members", []):
member = Member(data=mdata, guild=self, state=state) # type: ignore
if cache_joined or member.id == self_id:
self._add_member(member)
self._sync(guild)
self._large: Optional[bool] = None if member_count is None else self._member_count >= 250
self.owner_id: Optional[int] = utils.get_as_snowflake(guild, "owner_id")
self.afk_channel: Optional[VocalGuildChannel] = self.get_channel(utils.get_as_snowflake(guild, "afk_channel_id")) # type: ignore
for obj in guild.get("voice_states", []):
self._update_voice_state(obj, int(obj["channel_id"]))
for event in guild.get("guild_scheduled_events") or []:
self._store_scheduled_event(event)
self._premium_progress_bar_enabled: Optional[bool] = guild.get(
"premium_progress_bar_enabled"
)
self._safety_alerts_channel_id: Optional[int] = utils.get_as_snowflake(
guild, "safety_alerts_channel_id"
)
# TODO: refactor/remove?
def _sync(self, data: GuildPayload) -> None:
with contextlib.suppress(KeyError):
self._large = data["large"]
empty_tuple = ()
for presence in data.get("presences", []):
user_id = int(presence["user"]["id"])
member = self.get_member(user_id)
if member is not None:
member._presence_update(presence, empty_tuple) # type: ignore
if "channels" in data:
channels = data["channels"]
for c in channels:
factory, _ = _guild_channel_factory(c["type"])
if factory:
self._add_channel(factory(guild=self, data=c, state=self._state)) # type: ignore
if "threads" in data:
threads = data["threads"]
for thread in threads:
self._add_thread(Thread(guild=self, state=self._state, data=thread))
def channels(self) -> List[GuildChannel]:
"""List[:class:`abc.GuildChannel`]: A list of channels that belong to this guild."""
return list(self._channels.values())
def threads(self) -> List[Thread]:
"""List[:class:`Thread`]: A list of threads that you have permission to view.
.. versionadded:: 2.0
"""
return list(self._threads.values())
def large(self) -> bool:
""":class:`bool`: Indicates if the guild is a 'large' guild.
A large guild is defined as having more than ``large_threshold`` count
members, which for this library is set to the maximum of 250.
"""
if self._large is None:
try:
return self._member_count >= 250
except AttributeError:
return len(self._members) >= 250
return self._large
def invites_disabled(self) -> bool:
""":class:`bool`: Indicates if the guild's invites are paused.
.. versionadded:: 2.4
"""
return "INVITES_DISABLED" in self.features
def voice_channels(self) -> List[VoiceChannel]:
"""List[:class:`VoiceChannel`]: A list of voice channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, VoiceChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
def stage_channels(self) -> List[StageChannel]:
"""List[:class:`StageChannel`]: A list of stage channels that belong to this guild.
.. versionadded:: 1.7
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, StageChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
def me(self) -> Member:
""":class:`Member`: Similar to :attr:`Client.user` except an instance of :class:`Member`.
This is essentially used to get the member version of yourself.
"""
self_id = self._state.user.id # type: ignore
# The self member is *always* cached
return self.get_member(self_id) # type: ignore
def voice_client(self) -> Optional[VoiceProtocol]:
"""Optional[:class:`VoiceProtocol`]: Returns the :class:`VoiceProtocol` associated with this guild, if any."""
return self._state._get_voice_client(self.id)
def text_channels(self) -> List[TextChannel]:
"""List[:class:`TextChannel`]: A list of text channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, TextChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
def categories(self) -> List[CategoryChannel]:
"""List[:class:`CategoryChannel`]: A list of categories that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, CategoryChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
def forum_channels(self) -> List[ForumChannel]:
"""List[:class:`ForumChannel`]: A list of forum channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, ForumChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
def scheduled_events(self) -> List[ScheduledEvent]:
"""List[:class:`ScheduledEvent`]: A list of scheduled events in this guild.
.. versionadded:: 2.0
"""
return list(self._scheduled_events.values())
def premium_progress_bar_enabled(self) -> Optional[bool]:
"""Optional[:class:`bool`:] Whether the premium boost progress bar is enabled.
.. versionadded:: 2.6
"""
return self._premium_progress_bar_enabled
def by_category(self) -> List[ByCategoryItem]:
"""Returns every :class:`CategoryChannel` and their associated channels.
These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
``None``.
Returns
-------
List[Tuple[Optional[:class:`CategoryChannel`], List[:class:`abc.GuildChannel`]]]:
The categories and their associated channels.
"""
grouped: Dict[Optional[int], List[GuildChannel]] = {}
for channel in self._channels.values():
if isinstance(channel, CategoryChannel):
grouped.setdefault(channel.id, [])
continue
try:
grouped[channel.category_id].append(channel)
except KeyError:
grouped[channel.category_id] = [channel]
def key(t: ByCategoryItem) -> Tuple[Tuple[int, int], List[GuildChannel]]:
k, v = t
return ((k.position, k.id) if k else (-1, -1), v)
_get = self._channels.get
as_list: List[ByCategoryItem] = [(_get(k), v) for k, v in grouped.items()] # type: ignore
as_list.sort(key=key)
for _, channels in as_list:
channels.sort(key=lambda c: (c._sorting_bucket, c.position, c.id))
return as_list
def _resolve_channel(self, id: Optional[int], /) -> Optional[Union[GuildChannel, Thread]]:
if id is None:
return None
return self._channels.get(id) or self._threads.get(id)
def get_channel_or_thread(self, channel_id: int, /) -> Optional[Union[Thread, GuildChannel]]:
"""Returns a channel or thread with the given ID.
.. versionadded:: 2.0
Parameters
----------
channel_id: :class:`int`
The ID to search for.
Returns
-------
Optional[Union[:class:`Thread`, :class:`.abc.GuildChannel`]]
The returned channel or thread or ``None`` if not found.
"""
return self._channels.get(channel_id) or self._threads.get(channel_id)
def get_channel(self, channel_id: int, /) -> Optional[GuildChannel]:
"""Returns a channel with the given ID.
.. note::
This does *not* search for threads.
Parameters
----------
channel_id: :class:`int`
The ID to search for.
Returns
-------
Optional[:class:`.abc.GuildChannel`]
The returned channel or ``None`` if not found.
"""
return self._channels.get(channel_id)
def get_thread(self, thread_id: int, /) -> Optional[Thread]:
"""Returns a thread with the given ID.
.. versionadded:: 2.0
Parameters
----------
thread_id: :class:`int`
The ID to search for.
Returns
-------
Optional[:class:`Thread`]
The returned thread or ``None`` if not found.
"""
return self._threads.get(thread_id)
def system_channel(self) -> Optional[TextChannel]:
"""Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages.
If no channel is set, then this returns ``None``.
"""
channel_id = self._system_channel_id
return channel_id and self._channels.get(channel_id) # type: ignore
def system_channel_flags(self) -> SystemChannelFlags:
""":class:`SystemChannelFlags`: Returns the guild's system channel settings."""
return SystemChannelFlags._from_value(self._system_channel_flags)
def rules_channel(self) -> Optional[TextChannel]:
"""Optional[:class:`TextChannel`]: Return's the guild's channel used for the rules.
The guild must be a Community guild.
If no channel is set, then this returns ``None``.
.. versionadded:: 1.3
"""
channel_id = self._rules_channel_id
return channel_id and self._channels.get(channel_id) # type: ignore
def public_updates_channel(self) -> Optional[TextChannel]:
"""Optional[:class:`TextChannel`]: Return's the guild's channel where admins and
moderators of the guilds receive notices from Discord. The guild must be a
Community guild.
If no channel is set, then this returns ``None``.
.. versionadded:: 1.4
"""
channel_id = self._public_updates_channel_id
return channel_id and self._channels.get(channel_id) # type: ignore
def safety_alerts_channel(self) -> Optional[TextChannel]:
"""Optional[:class:`TextChannel`]: Returns the guild's channel where admins and
moderators of the guild receive safety alerts from Discord. The guild must be a
Community guild.
If no channel is set then this returns ``None``.
.. versionadded:: 2.6
"""
channel_id = self._safety_alerts_channel_id
return channel_id and self._channels.get(channel_id) # type: ignore
def emoji_limit(self) -> int:
""":class:`int`: The maximum number of emoji slots this guild has."""
more_emoji = 200 if "MORE_EMOJI" in self.features else 50
return max(more_emoji, self._PREMIUM_GUILD_LIMITS[self.premium_tier].emoji)
def sticker_limit(self) -> int:
""":class:`int`: The maximum number of sticker slots this guild has.
.. versionadded:: 2.0
"""
more_stickers = 60 if "MORE_STICKERS" in self.features else 5
return max(more_stickers, self._PREMIUM_GUILD_LIMITS[self.premium_tier].stickers)
def bitrate_limit(self) -> float:
""":class:`float`: The maximum bitrate for voice channels this guild can have."""
vip_guild = (
self._PREMIUM_GUILD_LIMITS[1].bitrate if "VIP_REGIONS" in self.features else 96e3
)
return max(vip_guild, self._PREMIUM_GUILD_LIMITS[self.premium_tier].bitrate)
def filesize_limit(self) -> int:
""":class:`int`: The maximum number of bytes files can have when uploaded to this guild."""
return self._PREMIUM_GUILD_LIMITS[self.premium_tier].filesize
def members(self) -> List[Member]:
"""List[:class:`Member`]: A list of members that belong to this guild."""
return list(self._members.values())
def bots(self) -> List[Member]:
"""List[:class:`Member`]: A list of bots that belong to this guild.
.. warning::
Due to a Discord limitation, in order for this attribute to remain up-to-date and
accurate, it requires :attr:`Intents.members` to be specified.
.. versionadded:: 2.0"""
return [m for m in self._members.values() if m.bot]
def humans(self) -> List[Member]:
"""List[:class:`Member`]: A list of user accounts that belong to this guild.
.. warning::
Due to a Discord limitation, in order for this attribute to remain up-to-date and
accurate, it requires :attr:`Intents.members` to be specified.
.. versionadded:: 2.0"""
return [m for m in self._members.values() if not m.bot]
def get_member(self, user_id: int, /) -> Optional[Member]:
"""Returns a member with the given ID.
Parameters
----------
user_id: :class:`int`
The ID to search for.
Returns
-------
Optional[:class:`Member`]
The member or ``None`` if not found.
"""
return self._members.get(user_id)
def premium_subscribers(self) -> List[Member]:
"""List[:class:`Member`]: A list of members who have "boosted" this guild."""
return [member for member in self.members if member.premium_since is not None]
def roles(self) -> List[Role]:
"""List[:class:`Role`]: Returns a :class:`list` of the guild's roles in hierarchy order.
The first element of this list will be the lowest role in the
hierarchy.
"""
return sorted(self._roles.values())
def get_role(self, role_id: int, /) -> Optional[Role]:
"""Returns a role with the given ID.
Parameters
----------
role_id: :class:`int`
The ID to search for.
Returns
-------
Optional[:class:`Role`]
The role or ``None`` if not found.
"""
return self._roles.get(role_id)
def default_role(self) -> Role:
""":class:`Role`: Gets the @everyone role that all members have by default."""
# The @everyone role is *always* given
return self.get_role(self.id) # type: ignore
def premium_subscriber_role(self) -> Optional[Role]:
"""Optional[:class:`Role`]: Gets the premium subscriber role, AKA "boost" role, in this guild.
.. versionadded:: 1.6
"""
for role in self._roles.values():
if role.is_premium_subscriber():
return role
return None
def self_role(self) -> Optional[Role]:
"""Optional[:class:`Role`]: Gets the role associated with this client's user, if any.
.. versionadded:: 1.6
"""
self_id = self._state.self_id
for role in self._roles.values():
tags = role.tags
if tags and tags.bot_id == self_id:
return role
return None
def stage_instances(self) -> List[StageInstance]:
"""List[:class:`StageInstance`]: Returns a :class:`list` of the guild's stage instances that
are currently running.
.. versionadded:: 2.0
"""
return list(self._stage_instances.values())
def get_stage_instance(self, stage_instance_id: int, /) -> Optional[StageInstance]:
"""Returns a stage instance with the given ID.
.. versionadded:: 2.0
Parameters
----------
stage_instance_id: :class:`int`
The ID to search for.
Returns
-------
Optional[:class:`StageInstance`]
The stage instance or ``None`` if not found.
"""
return self._stage_instances.get(stage_instance_id)
def owner(self) -> Optional[Member]:
"""Optional[:class:`Member`]: The member that owns the guild."""
return self.get_member(self.owner_id) # type: ignore
def icon(self) -> Optional[Asset]:
"""Optional[:class:`Asset`]: Returns the guild's icon asset, if available."""
if self._icon is None:
return None
return Asset._from_guild_icon(self._state, self.id, self._icon)
def banner(self) -> Optional[Asset]:
"""Optional[:class:`Asset`]: Returns the guild's banner asset, if available."""
if self._banner is None:
return None
return Asset._from_guild_image(self._state, self.id, self._banner, path="banners")
def splash(self) -> Optional[Asset]:
"""Optional[:class:`Asset`]: Returns the guild's invite splash asset, if available."""
if self._splash is None:
return None
return Asset._from_guild_image(self._state, self.id, self._splash, path="splashes")
def discovery_splash(self) -> Optional[Asset]:
"""Optional[:class:`Asset`]: Returns the guild's discovery splash asset, if available."""
if self._discovery_splash is None:
return None
return Asset._from_guild_image(
self._state, self.id, self._discovery_splash, path="discovery-splashes"
)
def member_count(self) -> Optional[int]:
"""Optional[:class:`int`]: Returns the true member count, if available.
.. warning::
Due to a Discord limitation, in order for this attribute to remain up-to-date and
accurate, it requires :attr:`Intents.members` to be specified.
"""
return getattr(self, "_member_count", None)
def chunked(self) -> bool:
""":class:`bool`: Returns a boolean indicating if the guild is "chunked".
A chunked guild means that :attr:`member_count` is equal to the
number of members stored in the internal :attr:`members` cache.
If this value returns ``False``, then you should request for
offline members.
"""
count = getattr(self, "_member_count", None)
if count is None:
return False
return count == len(self._members)
def shard_id(self) -> int:
""":class:`int`: Returns the shard ID for this guild if applicable."""
count = self._state.shard_count
if count is None:
return 0
return (self.id >> 22) % count
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the guild's creation time in UTC."""
return utils.snowflake_time(self.id)
def get_member_named(self, name: str, /) -> Optional[Member]:
"""Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. "Jake#0001"
or "Jake" will both do the lookup. However the former will give a more
precise result. Note that the discriminator must have all 4 digits
for this to work.
If a nickname is passed, then it is looked up via the nickname. Note
however, that a nickname + discriminator combo will not lookup the nickname
but rather the username + discriminator combo due to nickname + discriminator
not being unique.
If no member is found, ``None`` is returned.
Parameters
----------
name: :class:`str`
The name of the member to lookup with an optional discriminator.
Returns
-------
Optional[:class:`Member`]
The member in this guild with the associated name. If not found
then ``None`` is returned.
"""
result = None
members = self.members
if len(name) > 5 and name[-5] == "#":
# The 5 length is checking to see if #0000 is in the string,
# as a#0000 has a length of 6, the minimum for a potential
# discriminator lookup.
potential_discriminator = name[-4:]
# do the actual lookup and return if found
# if it isn't found then we'll do a full name lookup below.
result = utils.get(members, name=name[:-5], discriminator=potential_discriminator)
if result is not None:
return result
def pred(m: Member) -> bool:
return name in {m.nick, m.name}
return utils.find(pred, members)
def _create_channel(
self,
name: str,
channel_type: ChannelType,
overwrites: Dict[Union[Role, Member], PermissionOverwrite] = MISSING,
category: Optional[Snowflake] = None,
**options: Any,
):
if overwrites is MISSING:
overwrites = {}
elif not isinstance(overwrites, dict):
raise InvalidArgument("overwrites parameter expects a dict.")
perms = []
for target, perm in overwrites.items():
if not isinstance(perm, PermissionOverwrite):
raise InvalidArgument(
f"Expected PermissionOverwrite received {perm.__class__.__name__}"
)
allow, deny = perm.pair()
payload = {"allow": allow.value, "deny": deny.value, "id": target.id}
if isinstance(target, Role):
payload["type"] = abc._Overwrites.ROLE
else:
payload["type"] = abc._Overwrites.MEMBER
perms.append(payload)
parent_id = category.id if category else None
return self._state.http.create_channel(
self.id,
channel_type.value,
name=name,
parent_id=parent_id,
permission_overwrites=perms,
**options,
)
async def create_text_channel(
self,
name: str,
*,
reason: Optional[str] = None,
category: Optional[CategoryChannel] = None,
position: int = MISSING,
topic: str = MISSING,
slowmode_delay: int = MISSING,
nsfw: bool = MISSING,
overwrites: Dict[Union[Role, Member], PermissionOverwrite] = MISSING,
default_thread_slowmode_delay: int = MISSING,
) -> TextChannel:
"""|coro|
Creates a :class:`TextChannel` for the guild.
Note that you need the :attr:`~Permissions.manage_channels` permission
to create the channel.
The ``overwrites`` parameter can be used to create a 'secret'
channel upon creation. This parameter expects a :class:`dict` of
overwrites with the target (either a :class:`Member` or a :class:`Role`)
as the key and a :class:`PermissionOverwrite` as the value.
.. note::
Creating a channel of a specified position will not update the position of
other channels to follow suit. A follow-up call to :meth:`~TextChannel.edit`
will be required to update the position of the channel in the channel list.
Examples
--------
Creating a basic channel:
.. code-block:: python3
channel = await guild.create_text_channel('cool-channel')
Creating a "secret" channel:
.. code-block:: python3
overwrites = {
guild.default_role: nextcord.PermissionOverwrite(read_messages=False),
guild.me: nextcord.PermissionOverwrite(read_messages=True)
}
channel = await guild.create_text_channel('secret', overwrites=overwrites)
Parameters
----------
name: :class:`str`
The channel's name.
overwrites: Dict[Union[:class:`Role`, :class:`Member`], :class:`PermissionOverwrite`]
A :class:`dict` of target (either a role or a member) to
:class:`PermissionOverwrite` to apply upon creation of a channel.
Useful for creating secret channels.
category: Optional[:class:`CategoryChannel`]
The category to place the newly created channel under.
The permissions will be automatically synced to category if no
overwrites are provided.
position: :class:`int`
The position in the channel list. This is a number that starts
at 0. e.g. the top channel is position 0.
topic: :class:`str`
The new channel's topic.
slowmode_delay: :class:`int`
Specifies the slowmode rate limit for user in this channel, in seconds.
The maximum value possible is ``21600``.
nsfw: :class:`bool`
To mark the channel as NSFW or not.
reason: Optional[:class:`str`]
The reason for creating this channel. Shows up on the audit log.
Raises
------
Forbidden
You do not have the proper permissions to create this channel.
HTTPException
Creating the channel failed.
InvalidArgument
The permission overwrite information is not in proper form.
Returns
-------
:class:`TextChannel`
The channel that was just created.
"""
options = {}
if position is not MISSING:
options["position"] = position
if topic is not MISSING:
options["topic"] = topic
if slowmode_delay is not MISSING:
options["rate_limit_per_user"] = slowmode_delay
if nsfw is not MISSING:
options["nsfw"] = nsfw
if default_thread_slowmode_delay is not MISSING:
options["default_thread_rate_limit_per_user"] = default_thread_slowmode_delay
data = await self._create_channel(
name,
overwrites=overwrites,
channel_type=ChannelType.text,
category=category,
reason=reason,
**options,
)
channel = TextChannel(state=self._state, guild=self, data=data) # type: ignore
# payload *should* contain all text channel info
# temporarily add to the cache
self._channels[channel.id] = channel
return channel
async def create_voice_channel(
self,
name: str,
*,
reason: Optional[str] = None,
category: Optional[CategoryChannel] = None,
position: int = MISSING,
bitrate: int = MISSING,
user_limit: int = MISSING,
rtc_region: Optional[VoiceRegion] = MISSING,
video_quality_mode: VideoQualityMode = MISSING,
overwrites: Dict[Union[Role, Member], PermissionOverwrite] = MISSING,
) -> VoiceChannel:
"""|coro|
This is similar to :meth:`create_text_channel` except makes a :class:`VoiceChannel` instead.
Parameters
----------
name: :class:`str`
The channel's name.
overwrites: Dict[Union[:class:`Role`, :class:`Member`], :class:`PermissionOverwrite`]
A :class:`dict` of target (either a role or a member) to
:class:`PermissionOverwrite` to apply upon creation of a channel.
Useful for creating secret channels.
category: Optional[:class:`CategoryChannel`]
The category to place the newly created channel under.
The permissions will be automatically synced to category if no
overwrites are provided.
position: :class:`int`
The position in the channel list. This is a number that starts
at 0. e.g. the top channel is position 0.
bitrate: :class:`int`
The channel's preferred audio bitrate in bits per second.
user_limit: :class:`int`
The channel's limit for number of members that can be in a voice channel.
rtc_region: Optional[:class:`VoiceRegion`]
The region for the voice channel's voice communication.
A value of ``None`` indicates automatic voice region detection.
.. versionadded:: 1.7
video_quality_mode: :class:`VideoQualityMode`
The camera video quality for the voice channel's participants.
.. versionadded:: 2.0
reason: Optional[:class:`str`]
The reason for creating this channel. Shows up on the audit log.
Raises
------
Forbidden
You do not have the proper permissions to create this channel.
HTTPException
Creating the channel failed.
InvalidArgument
The permission overwrite information is not in proper form.
Returns
-------
:class:`VoiceChannel`
The channel that was just created.
"""
options = {}
if position is not MISSING:
options["position"] = position
if bitrate is not MISSING:
options["bitrate"] = bitrate
if user_limit is not MISSING:
options["user_limit"] = user_limit
if rtc_region is not MISSING:
options["rtc_region"] = None if rtc_region is None else str(rtc_region)
if video_quality_mode is not MISSING:
options["video_quality_mode"] = video_quality_mode.value
data = await self._create_channel(
name,
overwrites=overwrites,
channel_type=ChannelType.voice,
category=category,
reason=reason,
**options,
)
channel = VoiceChannel(state=self._state, guild=self, data=data) # type: ignore
# payload *should* contain all voice channel info
# temporarily add to the cache
self._channels[channel.id] = channel
return channel
async def create_stage_channel(
self,
name: str,
*,
topic: str,
position: int = MISSING,
overwrites: Dict[Union[Role, Member], PermissionOverwrite] = MISSING,
category: Optional[CategoryChannel] = None,
bitrate: Optional[int] = None,
user_limit: Optional[int] = None,
nsfw: Optional[bool] = None,
rtc_region: Optional[VoiceRegion] = MISSING,
video_quality_mode: Optional[VideoQualityMode] = None,
reason: Optional[str] = None,
) -> StageChannel:
"""|coro|
This is similar to :meth:`create_text_channel` except makes a :class:`StageChannel` instead.
.. versionadded:: 1.7
Parameters
----------
name: :class:`str`
The channel's name.
topic: :class:`str`
The new channel's topic.
overwrites: Dict[Union[:class:`Role`, :class:`Member`], :class:`PermissionOverwrite`]
A :class:`dict` of target (either a role or a member) to
:class:`PermissionOverwrite` to apply upon creation of a channel.
Useful for creating secret channels.
category: Optional[:class:`CategoryChannel`]
The category to place the newly created channel under.
The permissions will be automatically synced to category if no
overwrites are provided.
position: :class:`int`
The position in the channel list. This is a number that starts
at 0. e.g. the top channel is position 0.
bitrate: Optional[:class:`int`]
The channel's preferred audio bitrate in bits per second.
.. versionadded:: 2.6
user_limit: :class:`int`
The channel's limit for number of members that can be in a voice channel.
.. versionadded:: 2.6
rtc_region: Optional[:class:`VoiceRegion`]
The region for the voice channel's voice communication.
A value of ``None`` indicates automatic voice region detection.
.. versionadded:: 2.6
nsfw: :class:`bool`
To mark the channel as NSFW or not.
.. versionadded:: 2.6
video_quality_mode: :class:`VideoQualityMode`
The camera video quality for the voice channel's participants.
.. versionadded:: 2.6
reason: Optional[:class:`str`]
The reason for creating this channel. Shows up on the audit log.
Raises
------
Forbidden
You do not have the proper permissions to create this channel.
HTTPException
Creating the channel failed.
InvalidArgument
The permission overwrite information is not in proper form.
Returns
-------
:class:`StageChannel`
The channel that was just created.
"""
options: Dict[str, Any] = {
"topic": topic,
}
if position is not MISSING:
options["position"] = position
if bitrate is not None:
options["bitrate"] = bitrate
if user_limit is not None:
options["user_limit"] = user_limit
if rtc_region is not MISSING:
options["rtc_region"] = None if rtc_region is None else str(rtc_region)
if nsfw is not None:
options["nsfw"] = nsfw
if video_quality_mode is not None:
options["video_quality_mode"] = video_quality_mode.value
data = await self._create_channel(
name,
overwrites=overwrites,
channel_type=ChannelType.stage_voice,
category=category,
reason=reason,
**options,
)
channel = StageChannel(state=self._state, guild=self, data=data) # type: ignore
# payload *should* contain all stage channel info
# temporarily add to the cache
self._channels[channel.id] = channel
return channel
async def create_category(
self,
name: str,
*,
overwrites: Dict[Union[Role, Member], PermissionOverwrite] = MISSING,
reason: Optional[str] = None,
position: int = MISSING,
) -> CategoryChannel:
"""|coro|
Same as :meth:`create_text_channel` except makes a :class:`CategoryChannel` instead.
.. note::
The ``category`` parameter is not supported in this function since categories
cannot have categories.
Raises
------
Forbidden
You do not have the proper permissions to create this channel.
HTTPException
Creating the channel failed.
InvalidArgument
The permission overwrite information is not in proper form.
Returns
-------
:class:`CategoryChannel`
The channel that was just created.
"""
options: Dict[str, Any] = {}
if position is not MISSING:
options["position"] = position
data = await self._create_channel(
name, overwrites=overwrites, channel_type=ChannelType.category, reason=reason, **options
)
channel = CategoryChannel(state=self._state, guild=self, data=data) # type: ignore
# payload *should* contain all category channel info
# temporarily add to the cache
self._channels[channel.id] = channel
return channel
async def create_forum_channel(
self,
name: str,
*,
topic: str,
position: int = MISSING,
overwrites: Dict[Union[Role, Member], PermissionOverwrite] = MISSING,
category: Optional[CategoryChannel] = None,
default_thread_slowmode_delay: int = MISSING,
default_reaction: Optional[Union[Emoji, PartialEmoji, str]] = MISSING,
available_tags: List[ForumTag] = MISSING,
reason: Optional[str] = None,
default_sort_order: SortOrderType = MISSING,
default_forum_layout: Optional[ForumLayoutType] = None,
) -> ForumChannel:
"""|coro|
This is similar to :meth:`create_text_channel` except makes a :class:`ForumChannel` instead.
.. versionadded:: 2.1
.. versionchanged:: 2.5
Added the ``default_forum_layout`` parameter.
Parameters
----------
name: :class:`str`
The channel's name.
topic: :class:`str`
The new channel's topic.
overwrites: Dict[Union[:class:`Role`, :class:`Member`], :class:`PermissionOverwrite`]
A :class:`dict` of target (either a role or a member) to
:class:`PermissionOverwrite` to apply upon creation of a channel.
Useful for creating secret channels.
category: Optional[:class:`CategoryChannel`]
The category to place the newly created channel under.
The permissions will be automatically synced to category if no
overwrites are provided.
position: :class:`int`
The position in the channel list. This is a number that starts
at 0. e.g. the top channel is position 0.
reason: Optional[:class:`str`]
The reason for creating this channel. Shows up on the audit log.
default_sort_order: Optional[:class:`SortOrderType`]
The default sort order used to sort posts in this channel.
.. versionadded:: 2.3
default_thread_slowmode_delay: :class:`int`
The default slowmode delay for threads created in this channel.
Must be between ``0`` and ``21600``.
.. versionadded:: 2.4
default_reaction: Optional[Union[:class:`Emoji`, :class:`PartialEmoji`, :class:`str`]]
The default reaction for threads created in this channel.
.. versionadded:: 2.4
available_tags: List[:class:`ForumTag`]
The available tags for threads created in this channel.
.. versionadded:: 2.4
default_forum_layout: Optional[:class:`ForumLayoutType`]
The default layout type used to display posts in this forum.
Raises
------
Forbidden
You do not have the proper permissions to create this channel.
HTTPException
Creating the channel failed.
InvalidArgument
The permission overwrite information is not in proper form.
Returns
-------
:class:`ForumChannel`
The channel that was just created.
"""
options: Dict[str, Any] = {
"topic": topic,
}
if position is not MISSING:
options["position"] = position
if default_sort_order is not MISSING:
options["default_sort_order"] = default_sort_order.value
if default_thread_slowmode_delay is not MISSING:
options["default_thread_rate_limit_per_user"] = default_thread_slowmode_delay
if available_tags is not MISSING:
options["available_tags"] = [tag.payload for tag in available_tags]
if default_reaction is not MISSING:
if isinstance(default_reaction, str):
default_reaction = PartialEmoji.from_str(default_reaction)
if default_reaction is None:
options["default_reaction_emoji"] = None
else:
options["default_reaction_emoji"] = (
{
"emoji_id": default_reaction.id,
}
if default_reaction.id is not None
else {
"emoji_name": default_reaction.name,
}
)
if default_forum_layout is not None:
options["default_forum_layout"] = default_forum_layout.value
data = await self._create_channel(
name,
overwrites=overwrites,
channel_type=ChannelType.forum,
category=category,
reason=reason,
**options,
)
channel = ForumChannel(state=self._state, guild=self, data=data) # type: ignore
# payload *should* contain all forum channel info
# temporarily add to the cache
self._channels[channel.id] = channel
return channel
create_category_channel = create_category
async def leave(self) -> None:
"""|coro|
Leaves the guild.
.. note::
You cannot leave the guild that you own, you must delete it instead
via :meth:`delete`.
Raises
------
HTTPException
Leaving the guild failed.
"""
await self._state.http.leave_guild(self.id)
async def delete(self) -> None:
"""|coro|
Deletes the guild. You must be the guild owner to delete the
guild.
Raises
------
HTTPException
Deleting the guild failed.
Forbidden
You do not have permissions to delete the guild.
"""
await self._state.http.delete_guild(self.id)
async def edit(
self,
*,
reason: Optional[str] = MISSING,
name: str = MISSING,
description: Optional[str] = MISSING,
icon: Optional[Union[bytes, Asset, Attachment, File]] = MISSING,
banner: Optional[Union[bytes, Asset, Attachment, File]] = MISSING,
splash: Optional[Union[bytes, Asset, Attachment, File]] = MISSING,
discovery_splash: Optional[Union[bytes, Asset, Attachment, File]] = MISSING,
community: bool = MISSING,
region: Optional[Union[str, VoiceRegion]] = MISSING,
afk_channel: Optional[VoiceChannel] = MISSING,
owner: Snowflake = MISSING,
afk_timeout: int = MISSING,
default_notifications: NotificationLevel = MISSING,
verification_level: VerificationLevel = MISSING,
explicit_content_filter: ContentFilter = MISSING,
vanity_code: str = MISSING,
system_channel: Optional[TextChannel] = MISSING,
system_channel_flags: SystemChannelFlags = MISSING,
preferred_locale: str = MISSING,
rules_channel: Optional[TextChannel] = MISSING,
public_updates_channel: Optional[TextChannel] = MISSING,
invites_disabled: bool = MISSING,
premium_progress_bar_enabled: bool = MISSING,
) -> Guild:
r"""|coro|
Edits the guild.
You must have the :attr:`~Permissions.manage_guild` permission
to edit the guild.
.. versionchanged:: 1.4
The ``rules_channel`` and ``public_updates_channel`` keyword-only parameters were added.
.. versionchanged:: 2.0
The ``discovery_splash`` and ``community`` keyword-only parameters were added.
.. versionchanged:: 2.0
The newly updated guild is returned.
.. versionchanged:: 2.1
The ``icon``, ``banner``, ``splash``, ``discovery_splash``
parameters now accept :class:`File`, :class:`Attachment`, and :class:`Asset`.
.. versionchanged:: 2.4
The ``invites_disabled`` parameter has been added.
.. versionchanged:: 2.6
The ``premium_progress_bar_enabled`` parameter has been added.
Parameters
----------
name: :class:`str`
The new name of the guild.
description: Optional[:class:`str`]
The new description of the guild. Could be ``None`` for no description.
This is only available to guilds that contain ``PUBLIC`` in :attr:`Guild.features`.
icon: Optional[Union[:class:`bytes`, :class:`Asset`, :class:`Attachment`, :class:`File`]]
A :term:`py:bytes-like object`, :class:`File`, :class:`Attachment`, or :class:`Asset`
representing the icon. Only PNG/JPEG is supported. GIF is only available to guilds that contain
``ANIMATED_ICON`` in :attr:`Guild.features`. Could be ``None`` to denote removal of the icon.
banner: Optional[Union[:class:`bytes`, :class:`Asset`, :class:`Attachment`, :class:`File`]]
A :term:`py:bytes-like object`, :class:`File`, :class:`Attachment`, or :class:`Asset`
representing the banner. Could be ``None`` to denote removal of the banner.
This is only available to guilds that contain ``BANNER`` in :attr:`Guild.features`.
splash: Optional[Union[:class:`bytes`, :class:`Asset`, :class:`Attachment`, :class:`File`]]
A :term:`py:bytes-like object`, :class:`File`, :class:`Attachment`, or :class:`Asset`
representing the invite splash. Only PNG/JPEG supported. Could be ``None`` to denote removing the
splash. This is only available to guilds that contain ``INVITE_SPLASH`` in :attr:`Guild.features`.
discovery_splash: Optional[Union[:class:`bytes`, :class:`Asset`, :class:`Attachment`, :class:`File`]]
A :term:`py:bytes-like object`, :class:`File`, :class:`Attachment`, or :class:`Asset`
representing the discovery splash. Only PNG/JPEG supported. Could be ``None`` to denote removing the
splash. This is only available to guilds that contain ``DISCOVERABLE`` in :attr:`Guild.features`.
community: :class:`bool`
Whether the guild should be a Community guild. If set to ``True``\, both ``rules_channel``
and ``public_updates_channel`` parameters are required.
region: Union[:class:`str`, :class:`VoiceRegion`]
The new region for the guild's voice communication.
afk_channel: Optional[:class:`VoiceChannel`]
The new channel that is the AFK channel. Could be ``None`` for no AFK channel.
afk_timeout: :class:`int`
The number of seconds until someone is moved to the AFK channel.
owner: :class:`Member`
The new owner of the guild to transfer ownership to. Note that you must
be owner of the guild to do this.
verification_level: :class:`VerificationLevel`
The new verification level for the guild.
default_notifications: :class:`NotificationLevel`
The new default notification level for the guild.
explicit_content_filter: :class:`ContentFilter`
The new explicit content filter for the guild.
vanity_code: :class:`str`
The new vanity code for the guild.
system_channel: Optional[:class:`TextChannel`]
The new channel that is used for the system channel. Could be ``None`` for no system channel.
system_channel_flags: :class:`SystemChannelFlags`
The new system channel settings to use with the new system channel.
preferred_locale: :class:`str`
The new preferred locale for the guild. Used as the primary language in the guild.
If set, this must be an ISO 639 code, e.g. ``en-US`` or ``ja`` or ``zh-CN``.
rules_channel: Optional[:class:`TextChannel`]
The new channel that is used for rules. This is only available to
guilds that contain ``PUBLIC`` in :attr:`Guild.features`. Could be ``None`` for no rules
channel.
public_updates_channel: Optional[:class:`TextChannel`]
The new channel that is used for public updates from Discord. This is only available to
guilds that contain ``PUBLIC`` in :attr:`Guild.features`. Could be ``None`` for no
public updates channel.
invites_disabled: :class:`bool`
Whether the invites should be paused for the guild.
This will prevent new users from joining said guild.
premium_progress_bar_enabled: :class:`bool`
Whether the premium guild boost progress bar is enabled.
reason: Optional[:class:`str`]
The reason for editing this guild. Shows up on the audit log.
Raises
------
Forbidden
You do not have permissions to edit the guild.
HTTPException
Editing the guild failed.
InvalidArgument
The image format passed in to ``icon`` is invalid. It must be
PNG or JPG. This is also raised if you are not the owner of the
guild and request an ownership transfer.
Returns
-------
:class:`Guild`
The newly updated guild. Note that this has the same limitations as
mentioned in :meth:`Client.fetch_guild` and may not have full data.
"""
http = self._state.http
if vanity_code is not MISSING:
await http.change_vanity_code(self.id, vanity_code, reason=reason)
fields: Dict[str, Any] = {}
if name is not MISSING:
fields["name"] = name
if description is not MISSING:
fields["description"] = description
if preferred_locale is not MISSING:
fields["preferred_locale"] = preferred_locale
if afk_timeout is not MISSING:
fields["afk_timeout"] = afk_timeout
if icon is not MISSING:
fields["icon"] = await utils.obj_to_base64_data(icon)
if banner is not MISSING:
fields["banner"] = await utils.obj_to_base64_data(banner)
if splash is not MISSING:
fields["splash"] = await utils.obj_to_base64_data(splash)
if discovery_splash is not MISSING:
fields["discovery_splash"] = await utils.obj_to_base64_data(discovery_splash)
if default_notifications is not MISSING:
if not isinstance(default_notifications, NotificationLevel):
raise InvalidArgument(
"default_notifications field must be of type NotificationLevel"
)
fields["default_message_notifications"] = default_notifications.value
if afk_channel is not MISSING:
if afk_channel is None:
fields["afk_channel_id"] = afk_channel
else:
fields["afk_channel_id"] = afk_channel.id
if system_channel is not MISSING:
if system_channel is None:
fields["system_channel_id"] = system_channel
else:
fields["system_channel_id"] = system_channel.id
if rules_channel is not MISSING:
if rules_channel is None:
fields["rules_channel_id"] = rules_channel
else:
fields["rules_channel_id"] = rules_channel.id
if public_updates_channel is not MISSING:
if public_updates_channel is None:
fields["public_updates_channel_id"] = public_updates_channel
else:
fields["public_updates_channel_id"] = public_updates_channel.id
if owner is not MISSING:
if self.owner_id != self._state.self_id:
raise InvalidArgument("To transfer ownership you must be the owner of the guild.")
fields["owner_id"] = owner.id
if region is not MISSING:
fields["region"] = str(region)
if verification_level is not MISSING:
if not isinstance(verification_level, VerificationLevel):
raise InvalidArgument("verification_level field must be of type VerificationLevel")
fields["verification_level"] = verification_level.value
if explicit_content_filter is not MISSING:
if not isinstance(explicit_content_filter, ContentFilter):
raise InvalidArgument("explicit_content_filter field must be of type ContentFilter")
fields["explicit_content_filter"] = explicit_content_filter.value
if system_channel_flags is not MISSING:
if not isinstance(system_channel_flags, SystemChannelFlags):
raise InvalidArgument(
"system_channel_flags field must be of type SystemChannelFlags"
)
fields["system_channel_flags"] = system_channel_flags.value
if premium_progress_bar_enabled is not MISSING:
fields["premium_progress_bar_enabled"] = premium_progress_bar_enabled
if community is not MISSING:
features = []
if community:
if "rules_channel_id" in fields and "public_updates_channel_id" in fields:
features.append("COMMUNITY")
else:
raise InvalidArgument(
"community field requires both rules_channel and public_updates_channel fields to be provided"
)
fields["features"] = features
if invites_disabled is not MISSING:
features = self.features.copy()
if invites_disabled:
features.append("INVITES_DISABLED")
elif "INVITES_DISABLED" in features:
features.remove("INVITES_DISABLED")
fields["features"] = features
data = await http.edit_guild(self.id, reason=reason, **fields)
return Guild(data=data, state=self._state)
async def fetch_channels(self) -> Sequence[GuildChannel]:
"""|coro|
Retrieves all :class:`abc.GuildChannel` that the guild has.
.. note::
This method is an API call. For general usage, consider :attr:`channels` instead.
.. versionadded:: 1.2
Raises
------
InvalidData
An unknown channel type was received from Discord.
HTTPException
Retrieving the channels failed.
Returns
-------
Sequence[:class:`abc.GuildChannel`]
All channels in the guild.
"""
data = await self._state.http.get_all_guild_channels(self.id)
def convert(d):
factory, _ = _guild_channel_factory(d["type"])
if factory is None:
raise InvalidData("Unknown channel type {type} for channel ID {id}.".format_map(d))
return factory(guild=self, state=self._state, data=d)
return [convert(d) for d in data]
async def active_threads(self) -> List[Thread]:
"""|coro|
Returns a list of active :class:`Thread` that the client can access.
This includes both private and public threads.
.. versionadded:: 2.0
Raises
------
HTTPException
The request to get the active threads failed.
Returns
-------
List[:class:`Thread`]
The active threads
"""
data = await self._state.http.get_active_threads(self.id)
threads = [Thread(guild=self, state=self._state, data=d) for d in data.get("threads", [])]
thread_lookup: Dict[int, Thread] = {thread.id: thread for thread in threads}
for member in data.get("members", []):
thread = thread_lookup.get(int(member["id"]))
if thread is not None:
thread._add_member(ThreadMember(parent=thread, data=member))
return threads
# TODO: Remove Optional typing here when async iterators are refactored
def fetch_members(
self, *, limit: Optional[int] = 1000, after: Optional[SnowflakeTime] = None
) -> MemberIterator:
"""Retrieves an :class:`.AsyncIterator` that enables receiving the guild's members. In order to use this,
:meth:`Intents.members` must be enabled.
.. note::
This method is an API call. For general usage, consider :attr:`members` instead.
.. versionadded:: 1.3
All parameters are optional.
Parameters
----------
limit: Optional[:class:`int`]
The number of members to retrieve. Defaults to 1000.
Pass ``None`` to fetch all members. Note that this is potentially slow.
after: Optional[Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`]]
Retrieve members after this date or object.
If a datetime is provided, it is recommended to use a UTC aware datetime.
If the datetime is naive, it is assumed to be local time.
Raises
------
ClientException
The members intent is not enabled.
HTTPException
Getting the members failed.
Yields
------
:class:`.Member`
The member with the member data parsed.
Examples
--------
Usage ::
async for member in guild.fetch_members(limit=150):
print(member.name)
Flattening into a list ::
members = await guild.fetch_members(limit=150).flatten()
# members is now a list of Member...
"""
if not self._state._intents.members:
raise ClientException("Intents.members must be enabled to use this.")
return MemberIterator(self, limit=limit, after=after)
async def fetch_member(self, member_id: int, /) -> Member:
"""|coro|
Retrieves a :class:`Member` from a guild ID, and a member ID.
.. note::
This method is an API call. If you have :attr:`Intents.members` and member cache enabled, consider :meth:`get_member` instead.
Parameters
----------
member_id: :class:`int`
The member's ID to fetch from.
Raises
------
Forbidden
You do not have access to the guild.
HTTPException
Fetching the member failed.
Returns
-------
:class:`Member`
The member from the member ID.
"""
data = await self._state.http.get_member(self.id, member_id)
return Member(data=data, state=self._state, guild=self)
async def fetch_ban(self, user: Snowflake) -> BanEntry:
"""|coro|
Retrieves the :class:`BanEntry` for a user.
You must have the :attr:`~Permissions.ban_members` permission
to get this information.
Parameters
----------
user: :class:`abc.Snowflake`
The user to get ban information from.
Raises
------
Forbidden
You do not have proper permissions to get the information.
NotFound
This user is not banned.
HTTPException
An error occurred while fetching the information.
Returns
-------
:class:`BanEntry`
The :class:`BanEntry` object for the specified user.
"""
data: BanPayload = await self._state.http.get_ban(user.id, self.id)
return BanEntry(user=User(state=self._state, data=data["user"]), reason=data["reason"])
async def fetch_channel(self, channel_id: int, /) -> Union[GuildChannel, Thread]:
"""|coro|
Retrieves a :class:`.abc.GuildChannel` or :class:`.Thread` with the specified ID.
.. note::
This method is an API call. For general usage, consider :meth:`get_channel_or_thread` instead.
.. versionadded:: 2.0
Raises
------
:exc:`.InvalidData`
An unknown channel type was received from Discord
or the guild the channel belongs to is not the same
as the one in this object points to.
:exc:`.HTTPException`
Retrieving the channel failed.
:exc:`.NotFound`
Invalid Channel ID.
:exc:`.Forbidden`
You do not have permission to fetch this channel.
Returns
-------
Union[:class:`.abc.GuildChannel`, :class:`.Thread`]
The channel from the ID.
"""
data = await self._state.http.get_channel(channel_id)
factory, ch_type = _threaded_guild_channel_factory(data["type"])
if factory is None:
raise InvalidData("Unknown channel type {type} for channel ID {id}.".format_map(data))
if ch_type in (ChannelType.group, ChannelType.private):
raise InvalidData("Channel ID resolved to a private channel")
if TYPE_CHECKING:
data = cast(GuildChannelPayload, data)
guild_id = int(data["guild_id"])
if self.id != guild_id:
raise InvalidData("Guild ID resolved to a different guild")
channel: GuildChannel = factory(guild=self, state=self._state, data=data) # type: ignore
return channel
def bans(
self,
*,
limit: Optional[int] = 1000,
before: Optional[Snowflake] = None,
after: Optional[Snowflake] = None,
) -> BanIterator:
"""Returns an :class:`~nextcord.AsyncIterator` that enables receiving the destination's bans.
You must have the :attr:`~Permissions.ban_members` permission to get this information.
.. versionchanged:: 2.0
Due to a breaking change in Discord's API, this now returns an :class:`~nextcord.AsyncIterator` instead of a :class:`list`.
Examples
--------
Usage ::
counter = 0
async for ban in guild.bans(limit=200):
if not ban.user.bot:
counter += 1
Flattening into a list: ::
bans = await guild.bans(limit=123).flatten()
# bans is now a list of BanEntry...
All parameters are optional.
Parameters
----------
limit: Optional[:class:`int`]
The number of bans to retrieve.
If ``None``, it retrieves every ban in the guild. Note, however,
that this would make a slow operation.
Defaults to 1000.
before: Optional[:class:`~nextcord.abc.Snowflake`]
Retrieve bans before this user.
after: Optional[:class:`~nextcord.abc.Snowflake`]
Retrieve bans after this user.
Raises
------
~nextcord.Forbidden
You do not have permissions to get the bans.
~nextcord.HTTPException
An error occurred while fetching the bans.
Yields
------
:class:`~nextcord.BanEntry`
The ban with the ban data parsed.
"""
return BanIterator(self, limit=limit, before=before, after=after)
async def prune_members(
self,
*,
days: int,
compute_prune_count: bool = True,
roles: List[Snowflake] = MISSING,
reason: Optional[str] = None,
) -> Optional[int]:
r"""|coro|
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
``days`` number of days and they have no roles.
You must have the :attr:`~Permissions.kick_members` permission
to use this.
To check how many members you would prune without actually pruning,
see the :meth:`estimate_pruned_members` function.
To prune members that have specific roles see the ``roles`` parameter.
.. versionchanged:: 1.4
The ``roles`` keyword-only parameter was added.
Parameters
----------
days: :class:`int`
The number of days before counting as inactive.
reason: Optional[:class:`str`]
The reason for doing this action. Shows up on the audit log.
compute_prune_count: :class:`bool`
Whether to compute the prune count. This defaults to ``True``
which makes it prone to timeouts in very large guilds. In order
to prevent timeouts, you must set this to ``False``. If this is
set to ``False``\, then this function will always return ``None``.
roles: List[:class:`abc.Snowflake`]
A list of :class:`abc.Snowflake` that represent roles to include in the pruning process. If a member
has a role that is not specified, they'll be excluded.
Raises
------
Forbidden
You do not have permissions to prune members.
HTTPException
An error occurred while pruning members.
InvalidArgument
An integer was not passed for ``days``.
Returns
-------
Optional[:class:`int`]
The number of members pruned. If ``compute_prune_count`` is ``False``
then this returns ``None``.
"""
if not isinstance(days, int):
raise InvalidArgument(
f"Expected int for ``days``, received {days.__class__.__name__} instead."
)
role_ids = [str(role.id) for role in roles] if roles else []
data = await self._state.http.prune_members(
self.id, days, compute_prune_count=compute_prune_count, roles=role_ids, reason=reason
)
return data["pruned"]
async def templates(self) -> List[Template]:
"""|coro|
Gets the list of templates from this guild.
Requires :attr:`~.Permissions.manage_guild` permissions.
.. versionadded:: 1.7
Raises
------
Forbidden
You don't have permissions to get the templates.
Returns
-------
List[:class:`Template`]
The templates for this guild.
"""
from .template import Template
data = await self._state.http.guild_templates(self.id)
return [Template(data=d, state=self._state) for d in data]
async def webhooks(self) -> List[Webhook]:
"""|coro|
Gets the list of webhooks from this guild.
Requires :attr:`~.Permissions.manage_webhooks` permissions.
Raises
------
Forbidden
You don't have permissions to get the webhooks.
Returns
-------
List[:class:`Webhook`]
The webhooks for this guild.
"""
from .webhook import Webhook
data = await self._state.http.guild_webhooks(self.id)
return [Webhook.from_state(d, state=self._state) for d in data]
async def estimate_pruned_members(
self, *, days: int, roles: List[Snowflake] = MISSING
) -> Optional[int]:
"""|coro|
Similar to :meth:`prune_members` except instead of actually
pruning members, it returns how many members it would prune
from the guild had it been called.
Parameters
----------
days: :class:`int`
The number of days before counting as inactive.
roles: List[:class:`abc.Snowflake`]
A list of :class:`abc.Snowflake` that represent roles to include in the estimate. If a member
has a role that is not specified, they'll be excluded.
.. versionadded:: 1.7
Raises
------
Forbidden
You do not have permissions to prune members.
HTTPException
An error occurred while fetching the prune members estimate.
InvalidArgument
An integer was not passed for ``days``.
Returns
-------
:class:`int`
The number of members estimated to be pruned.
"""
if not isinstance(days, int):
raise InvalidArgument(
f"Expected int for ``days``, received {days.__class__.__name__} instead."
)
role_ids = [str(role.id) for role in roles] if roles else []
data = await self._state.http.estimate_pruned_members(self.id, days, role_ids)
return data["pruned"]
async def invites(self) -> List[Invite]:
"""|coro|
Returns a list of all active instant invites from the guild.
You must have the :attr:`~Permissions.manage_guild` permission to get
this information.
Raises
------
Forbidden
You do not have proper permissions to get the information.
HTTPException
An error occurred while fetching the information.
Returns
-------
List[:class:`Invite`]
The list of invites that are currently active.
.. note::
This method does not include the Guild's vanity URL.
To get the vanity URL :class:`Invite`, refer to :meth:`Guild.vanity_invite`.
"""
data = await self._state.http.invites_from(self.id)
result = []
for invite in data:
channel = self.get_channel(int(invite["channel"]["id"]))
result.append(Invite(state=self._state, data=invite, guild=self, channel=channel))
return result
async def create_template(self, *, name: str, description: str = MISSING) -> Template:
"""|coro|
Creates a template for the guild.
You must have the :attr:`~Permissions.manage_guild` permission to
do this.
.. versionadded:: 1.7
Parameters
----------
name: :class:`str`
The name of the template.
description: :class:`str`
The description of the template.
"""
from .template import Template
payload: CreateTemplate = {"name": name, "icon": None}
if description:
payload["description"] = description
data = await self._state.http.create_template(self.id, payload)
return Template(state=self._state, data=data)
async def create_integration(self, *, type: IntegrationType, id: int) -> None:
"""|coro|
Attaches an integration to the guild.
You must have the :attr:`~Permissions.manage_guild` permission to
do this.
.. versionadded:: 1.4
Parameters
----------
type: :class:`str`
The integration type (e.g. Twitch).
id: :class:`int`
The integration ID.
Raises
------
Forbidden
You do not have permission to create the integration.
HTTPException
The account could not be found.
"""
await self._state.http.create_integration(self.id, type, id)
async def integrations(self) -> List[Integration]:
"""|coro|
Returns a list of all integrations attached to the guild.
You must have the :attr:`~Permissions.manage_guild` permission to
do this.
.. versionadded:: 1.4
Raises
------
Forbidden
You do not have permission to create the integration.
HTTPException
Fetching the integrations failed.
Returns
-------
List[:class:`Integration`]
The list of integrations that are attached to the guild.
"""
data = await self._state.http.get_all_integrations(self.id)
def convert(d):
factory, _ = _integration_factory(d["type"])
return factory(guild=self, data=d)
return [convert(d) for d in data]
async def fetch_stickers(self) -> List[GuildSticker]:
r"""|coro|
Retrieves a list of all :class:`Sticker`\s for the guild.
.. versionadded:: 2.0
.. note::
This method is an API call. For general usage, consider :attr:`stickers` instead.
Raises
------
HTTPException
An error occurred fetching the stickers.
Returns
-------
List[:class:`GuildSticker`]
The retrieved stickers.
"""
data = await self._state.http.get_all_guild_stickers(self.id)
return [GuildSticker(state=self._state, data=d) for d in data]
async def fetch_sticker(self, sticker_id: int, /) -> GuildSticker:
"""|coro|
Retrieves a custom :class:`Sticker` from the guild.
.. versionadded:: 2.0
.. note::
This method is an API call.
For general usage, consider iterating over :attr:`stickers` instead.
Parameters
----------
sticker_id: :class:`int`
The sticker's ID.
Raises
------
NotFound
The sticker requested could not be found.
HTTPException
An error occurred fetching the sticker.
Returns
-------
:class:`GuildSticker`
The retrieved sticker.
"""
data = await self._state.http.get_guild_sticker(self.id, sticker_id)
return GuildSticker(state=self._state, data=data)
async def create_sticker(
self,
*,
name: str,
description: Optional[str] = None,
emoji: str,
file: File,
reason: Optional[str] = None,
) -> GuildSticker:
"""|coro|
Creates a :class:`Sticker` for the guild.
You must have :attr:`~Permissions.manage_emojis_and_stickers` permission to
do this.
.. versionadded:: 2.0
Parameters
----------
name: :class:`str`
The sticker name. Must be at least 2 characters.
description: Optional[:class:`str`]
The sticker's description. Can be ``None``.
emoji: :class:`str`
The name of a unicode emoji that represents the sticker's expression.
file: :class:`File`
The file of the sticker to upload.
reason: :class:`str`
The reason for creating this sticker. Shows up on the audit log.
Raises
------
Forbidden
You are not allowed to create stickers.
HTTPException
An error occurred creating a sticker.
Returns
-------
:class:`GuildSticker`
The created sticker.
"""
if description is None:
description = ""
try:
emoji = unicodedata.name(emoji)
except TypeError:
pass
else:
emoji = emoji.replace(" ", "_")
payload: CreateGuildSticker = {
"name": name,
"description": description,
"tags": emoji,
}
data = await self._state.http.create_guild_sticker(self.id, payload, file, reason=reason)
return self._state.store_sticker(self, data)
async def delete_sticker(self, sticker: Snowflake, *, reason: Optional[str] = None) -> None:
"""|coro|
Deletes the custom :class:`Sticker` from the guild.
You must have :attr:`~Permissions.manage_emojis_and_stickers` permission to
do this.
.. versionadded:: 2.0
Parameters
----------
sticker: :class:`abc.Snowflake`
The sticker you are deleting.
reason: Optional[:class:`str`]
The reason for deleting this sticker. Shows up on the audit log.
Raises
------
Forbidden
You are not allowed to delete stickers.
HTTPException
An error occurred deleting the sticker.
"""
await self._state.http.delete_guild_sticker(self.id, sticker.id, reason)
async def fetch_emojis(self) -> List[Emoji]:
r"""|coro|
Retrieves all custom :class:`Emoji`\s from the guild.
.. note::
This method is an API call. For general usage, consider :attr:`emojis` instead.
Raises
------
HTTPException
An error occurred fetching the emojis.
Returns
-------
List[:class:`Emoji`]
The retrieved emojis.
"""
data = await self._state.http.get_all_custom_emojis(self.id)
return [Emoji(guild=self, state=self._state, data=d) for d in data]
async def fetch_emoji(self, emoji_id: int, /) -> Emoji:
"""|coro|
Retrieves a custom :class:`Emoji` from the guild.
.. note::
This method is an API call.
For general usage, consider iterating over :attr:`emojis` instead.
Parameters
----------
emoji_id: :class:`int`
The emoji's ID.
Raises
------
NotFound
The emoji requested could not be found.
HTTPException
An error occurred fetching the emoji.
Returns
-------
:class:`Emoji`
The retrieved emoji.
"""
data = await self._state.http.get_custom_emoji(self.id, emoji_id)
return Emoji(guild=self, state=self._state, data=data)
async def create_custom_emoji(
self,
*,
name: str,
image: Union[bytes, Asset, Attachment, File],
roles: List[Role] = MISSING,
reason: Optional[str] = None,
) -> Emoji:
r"""|coro|
Creates a custom :class:`Emoji` for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild,
unless the guild has the ``MORE_EMOJI`` feature which extends the limit to 200.
You must have the :attr:`~Permissions.manage_emojis` permission to
do this.
.. versionchanged:: 2.1
The ``image`` parameter now accepts :class:`File`, :class:`Attachment`, and :class:`Asset`.
Parameters
----------
name: :class:`str`
The emoji name. Must be at least 2 characters.
image: Union[:class:`bytes`, :class:`Asset`, :class:`Attachment`, :class:`File`]
The :term:`py:bytes-like object`, :class:`File`, :class:`Attachment`, or :class:`Asset`
representing the image data to use. Only JPG, PNG and GIF images are supported.
roles: List[:class:`Role`]
A :class:`list` of :class:`Role`\s that can use this emoji. Leave empty to make it available to everyone.
reason: Optional[:class:`str`]
The reason for creating this emoji. Shows up on the audit log.
Raises
------
Forbidden
You are not allowed to create emojis.
HTTPException
An error occurred creating an emoji.
Returns
-------
:class:`Emoji`
The created emoji.
"""
img_base64 = await utils.obj_to_base64_data(image)
role_ids: SnowflakeList
role_ids = [role.id for role in roles] if roles else []
data = await self._state.http.create_custom_emoji(
self.id, name, img_base64, roles=role_ids, reason=reason
)
return self._state.store_emoji(self, data)
async def delete_emoji(self, emoji: Snowflake, *, reason: Optional[str] = None) -> None:
"""|coro|
Deletes the custom :class:`Emoji` from the guild.
You must have :attr:`~Permissions.manage_emojis` permission to
do this.
Parameters
----------
emoji: :class:`abc.Snowflake`
The emoji you are deleting.
reason: Optional[:class:`str`]
The reason for deleting this emoji. Shows up on the audit log.
Raises
------
Forbidden
You are not allowed to delete emojis.
HTTPException
An error occurred deleting the emoji.
"""
await self._state.http.delete_custom_emoji(self.id, emoji.id, reason=reason)
async def fetch_roles(self, *, cache: bool = False) -> List[Role]:
"""|coro|
Retrieves all :class:`Role` that the guild has.
.. note::
This method is an API call. For general usage, consider :attr:`roles` instead.
Parameters
----------
cache: bool
Whether or not to also update this guilds
role cache. Defaults to ``False``.
Raises
------
HTTPException
Retrieving the roles failed.
Returns
-------
List[:class:`Role`]
All roles in the guild.
"""
data = await self._state.http.get_roles(self.id)
roles = [Role(guild=self, state=self._state, data=d) for d in data]
if cache:
self._roles: Dict[int, Role] = {}
for role in roles:
self._roles[role.id] = role
return roles
async def create_role(
self,
*,
reason: Optional[str] = ...,
name: str = ...,
permissions: Permissions = ...,
colour: Union[Colour, int] = ...,
hoist: bool = ...,
mentionable: bool = ...,
icon: Optional[Union[str, bytes, Asset, Attachment, File]] = ...,
) -> Role:
...
async def create_role(
self,
*,
reason: Optional[str] = ...,
name: str = ...,
permissions: Permissions = ...,
color: Union[Colour, int] = ...,
hoist: bool = ...,
mentionable: bool = ...,
icon: Optional[Union[str, bytes, Asset, Attachment, File]] = ...,
) -> Role:
...
async def create_role(
self,
*,
name: str = MISSING,
permissions: Permissions = MISSING,
color: Union[Colour, int] = MISSING,
colour: Union[Colour, int] = MISSING,
hoist: bool = MISSING,
mentionable: bool = MISSING,
icon: Optional[Union[str, bytes, Asset, Attachment, File]] = MISSING,
reason: Optional[str] = None,
) -> Role:
"""|coro|
Creates a :class:`Role` for the guild.
All fields are optional.
You must have the :attr:`~Permissions.manage_roles` permission to
do this.
.. versionchanged:: 1.6
Can now pass ``int`` to ``colour`` keyword-only parameter.
.. versionchanged:: 2.1
The ``icon`` parameter now accepts :class:`File`, :class:`Attachment`, and :class:`Asset`.
Parameters
----------
name: :class:`str`
The role name. Defaults to 'new role'.
permissions: :class:`Permissions`
The permissions to have. Defaults to no permissions.
colour: Union[:class:`Colour`, :class:`int`]
The colour for the role. Defaults to :meth:`Colour.default`.
This is aliased to ``color`` as well.
hoist: :class:`bool`
Indicates if the role should be shown separately in the member list.
Defaults to ``False``.
mentionable: :class:`bool`
Indicates if the role should be mentionable by others.
Defaults to ``False``.
icon: Optional[Union[:class:`str`, :class:`bytes`, :class:`Asset`, :class:`Attachment`, :class:`File`]]
The icon of the role. Supports unicode emojis and images
reason: Optional[:class:`str`]
The reason for creating this role. Shows up on the audit log.
Raises
------
Forbidden
You do not have permissions to create the role.
HTTPException
Creating the role failed.
InvalidArgument
An invalid keyword argument was given.
Returns
-------
:class:`Role`
The newly created role.
"""
fields: Dict[str, Any] = {}
if permissions is not MISSING:
fields["permissions"] = str(permissions.value)
else:
fields["permissions"] = "0"
actual_colour = colour or color or Colour.default()
if isinstance(actual_colour, int):
fields["color"] = actual_colour
else:
fields["color"] = actual_colour.value
if hoist is not MISSING:
fields["hoist"] = hoist
if mentionable is not MISSING:
fields["mentionable"] = mentionable
if name is not MISSING:
fields["name"] = name
if icon is not MISSING:
if isinstance(icon, str):
fields["unicode_emoji"] = icon
else:
fields["icon"] = await utils.obj_to_base64_data(icon)
data = await self._state.http.create_role(self.id, reason=reason, **fields)
return Role(guild=self, data=data, state=self._state)
async def edit_role_positions(
self, positions: Dict[Snowflake, int], *, reason: Optional[str] = None
) -> List[Role]:
"""|coro|
Bulk edits a list of :class:`Role` in the guild.
You must have the :attr:`~Permissions.manage_roles` permission to
do this.
.. versionadded:: 1.4
Example:
.. code-block:: python3
positions = {
bots_role: 1, # penultimate role
tester_role: 2,
admin_role: 6
}
await guild.edit_role_positions(positions=positions)
Parameters
----------
positions
A :class:`dict` of :class:`Role` to :class:`int` to change the positions
of each given role.
reason: Optional[:class:`str`]
The reason for editing the role positions. Shows up on the audit log.
Raises
------
Forbidden
You do not have permissions to move the roles.
HTTPException
Moving the roles failed.
InvalidArgument
An invalid keyword argument was given.
Returns
-------
List[:class:`Role`]
A list of all the roles in the guild.
"""
if not isinstance(positions, dict):
raise InvalidArgument("positions parameter expects a dict.")
role_positions: List[RolePositionUpdate] = []
for role, position in positions.items():
payload: RolePositionUpdate = {"id": role.id, "position": position}
role_positions.append(payload)
data = await self._state.http.move_role_position(self.id, role_positions, reason=reason)
roles: List[Role] = []
for d in data:
role = Role(guild=self, data=d, state=self._state)
roles.append(role)
self._roles[role.id] = role
return roles
async def kick(self, user: Snowflake, *, reason: Optional[str] = None) -> None:
"""|coro|
Kicks a user from the guild.
The user must meet the :class:`abc.Snowflake` abc.
You must have the :attr:`~Permissions.kick_members` permission to
do this.
Parameters
----------
user: :class:`abc.Snowflake`
The user to kick from their guild.
reason: Optional[:class:`str`]
The reason the user got kicked.
Raises
------
Forbidden
You do not have the proper permissions to kick.
HTTPException
Kicking failed.
"""
await self._state.http.kick(user.id, self.id, reason=reason)
async def ban(
self,
user: Snowflake,
*,
reason: Optional[str] = None,
delete_message_seconds: Optional[int] = None,
delete_message_days: Optional[Literal[0, 1, 2, 3, 4, 5, 6, 7]] = None,
) -> None:
"""|coro|
Bans a user from the guild.
The user must meet the :class:`abc.Snowflake` abc.
You must have the :attr:`~Permissions.ban_members` permission to
do this.
For backwards compatibility reasons, by default one day worth of messages will be deleted.
.. warning::
delete_message_days is deprecated and will be removed in a future version.
Use delete_message_seconds instead.
Parameters
----------
user: :class:`abc.Snowflake`
The user to ban from their guild.
delete_message_seconds: Optional[:class:`int`]
The number of seconds worth of messages to delete from the user
in the guild. The minimum is 0 and the maximum is 604800 (7 days).
.. versionadded:: 2.3
delete_message_days: Optional[:class:`int`]
The number of days worth of messages to delete from the user
in the guild. The minimum is 0 and the maximum is 7.
.. deprecated:: 2.3
reason: Optional[:class:`str`]
The reason the user got banned.
Raises
------
Forbidden
You do not have the proper permissions to ban.
HTTPException
Banning failed.
"""
if delete_message_days is not None and delete_message_seconds is not None:
raise InvalidArgument(
"Cannot pass both delete_message_days and delete_message_seconds."
)
if delete_message_days is not None:
warnings.warn(
DeprecationWarning(
"delete_message_days is deprecated, use delete_message_seconds instead.",
),
stacklevel=2,
)
delete_message_seconds = delete_message_days * 24 * 60 * 60
elif delete_message_seconds is None:
# Default to one day
delete_message_seconds = 24 * 60 * 60
await self._state.http.ban(user.id, self.id, delete_message_seconds, reason=reason)
async def unban(self, user: Snowflake, *, reason: Optional[str] = None) -> None:
"""|coro|
Unbans a user from the guild.
The user must meet the :class:`abc.Snowflake` abc.
You must have the :attr:`~Permissions.ban_members` permission to
do this.
Parameters
----------
user: :class:`abc.Snowflake`
The user to unban.
reason: Optional[:class:`str`]
The reason for doing this action. Shows up on the audit log.
Raises
------
Forbidden
You do not have the proper permissions to unban.
HTTPException
Unbanning failed.
"""
await self._state.http.unban(user.id, self.id, reason=reason)
async def vanity_invite(self) -> Optional[Invite]:
"""|coro|
Returns the guild's special vanity invite.
The guild must have ``VANITY_URL`` in :attr:`~Guild.features`.
You must have the :attr:`~Permissions.manage_guild` permission to use
this as well.
Raises
------
Forbidden
You do not have the proper permissions to get this.
HTTPException
Retrieving the vanity invite failed.
Returns
-------
Optional[:class:`Invite`]
The special vanity invite. If ``None`` then the guild does not
have a vanity invite set.
"""
# we start with { code: abc }
payload = await self._state.http.get_vanity_code(self.id)
if not payload["code"]:
return None
# get the vanity URL channel since default channels aren't
# reliable or a thing anymore
data = await self._state.http.get_invite(payload["code"])
channel = self.get_channel(int(data["channel"]["id"]))
payload["revoked"] = False
payload["temporary"] = False
payload["max_uses"] = 0
payload["max_age"] = 0
payload["uses"] = payload.get("uses", 0)
return Invite(state=self._state, data=payload, guild=self, channel=channel)
# TODO: use MISSING when async iterators get refactored
def audit_logs(
self,
*,
limit: Optional[int] = 100,
before: Optional[SnowflakeTime] = None,
after: Optional[SnowflakeTime] = None,
oldest_first: Optional[bool] = None,
user: Optional[Snowflake] = None,
action: Optional[AuditLogAction] = None,
) -> AuditLogIterator:
"""Returns an :class:`AsyncIterator` that enables receiving the guild's audit logs.
You must have the :attr:`~Permissions.view_audit_log` permission to use this.
Examples
--------
Getting the first 100 entries: ::
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
Getting entries for a specific action: ::
async for entry in guild.audit_logs(action=nextcord.AuditLogAction.ban):
print(f'{entry.user} banned {entry.target}')
Getting entries made by a specific user: ::
entries = await guild.audit_logs(limit=None, user=guild.me).flatten()
await channel.send(f'I made {len(entries)} moderation actions.')
Parameters
----------
limit: Optional[:class:`int`]
The number of entries to retrieve. If ``None`` retrieve all entries.
before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]]
Retrieve entries before this date or entry.
If a datetime is provided, it is recommended to use a UTC aware datetime.
If the datetime is naive, it is assumed to be local time.
after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]]
Retrieve entries after this date or entry.
If a datetime is provided, it is recommended to use a UTC aware datetime.
If the datetime is naive, it is assumed to be local time.
oldest_first: Optional[:class:`bool`]
If set to ``True``, return entries in oldest->newest order. Defaults to ``True`` if
``after`` is specified, otherwise ``False``.
user: Optional[:class:`abc.Snowflake`]
The moderator to filter entries from.
action: Optional[:class:`AuditLogAction`]
The action to filter with.
Raises
------
Forbidden
You are not allowed to fetch audit logs
HTTPException
An error occurred while fetching the audit logs.
Yields
------
:class:`AuditLogEntry`
The audit log entry.
"""
user_id = user.id if user is not None else None
return AuditLogIterator(
self,
before=before,
after=after,
limit=limit,
oldest_first=oldest_first,
user_id=user_id,
action_type=action,
)
async def widget(self) -> Widget:
"""|coro|
Returns the widget of the guild.
.. note::
The guild must have the widget enabled to get this information.
Raises
------
Forbidden
The widget for this guild is disabled.
HTTPException
Retrieving the widget failed.
Returns
-------
:class:`Widget`
The guild's widget.
"""
data = await self._state.http.get_widget(self.id)
return Widget(state=self._state, data=data)
async def edit_widget(
self, *, enabled: bool = MISSING, channel: Optional[Snowflake] = MISSING
) -> None:
"""|coro|
Edits the widget of the guild.
You must have the :attr:`~Permissions.manage_guild` permission to
use this
.. versionadded:: 2.0
Parameters
----------
enabled: :class:`bool`
Whether to enable the widget for the guild.
channel: Optional[:class:`~nextcord.abc.Snowflake`]
The new widget channel. ``None`` removes the widget channel.
Raises
------
Forbidden
You do not have permission to edit the widget.
HTTPException
Editing the widget failed.
"""
payload = {}
if channel is not MISSING:
payload["channel_id"] = None if channel is None else channel.id
if enabled is not MISSING:
payload["enabled"] = enabled
await self._state.http.edit_widget(self.id, payload=payload)
async def chunk(self, *, cache: bool = True) -> Optional[List[Member]]:
"""|coro|
Requests all members that belong to this guild. In order to use this,
:meth:`Intents.members` must be enabled.
This is a websocket operation and can be slow.
.. versionadded:: 1.5
Parameters
----------
cache: :class:`bool`
Whether to cache the members as well.
Raises
------
ClientException
The members intent is not enabled.
Returns
-------
Optional[List[:class:`Member`]]
Returns a list of all the members in the guild.
"""
if not self._state._intents.members:
raise ClientException("Intents.members must be enabled to use this.")
if not self._state.is_guild_evicted(self):
members = await self._state.chunk_guild(self, cache=cache)
if isinstance(members, Future):
members = await members
return members
return None
async def query_members(
self,
query: Optional[str] = None,
*,
limit: int = 5,
user_ids: Optional[List[int]] = None,
presences: bool = False,
cache: bool = True,
) -> List[Member]:
"""|coro|
Request members that belong to this guild whose username starts with
the query given.
This is a websocket operation and can be slow.
.. versionadded:: 1.3
Parameters
----------
query: Optional[:class:`str`]
The string that the username's start with.
limit: :class:`int`
The maximum number of members to send back. This must be
a number between 5 and 100.
presences: :class:`bool`
Whether to request for presences to be provided. This defaults
to ``False``.
.. versionadded:: 1.6
cache: :class:`bool`
Whether to cache the members internally. This makes operations
such as :meth:`get_member` work for those that matched.
user_ids: Optional[List[:class:`int`]]
List of user IDs to search for. If the user ID is not in the guild then it won't be returned.
.. versionadded:: 1.4
Raises
------
asyncio.TimeoutError
The query timed out waiting for the members.
ValueError
Invalid parameters were passed to the function
ClientException
The presences intent is not enabled.
Returns
-------
List[:class:`Member`]
The list of members that have matched the query.
"""
if presences and not self._state._intents.presences:
raise ClientException("Intents.presences must be enabled to use this.")
if not query:
if query == "":
raise ValueError("Cannot pass empty query string.")
if user_ids is None:
raise ValueError("Must pass either query or user_ids")
if user_ids is not None and query is not None:
raise ValueError("Cannot pass both query and user_ids")
if user_ids is not None and not user_ids:
raise ValueError("user_ids must contain at least 1 value")
limit = min(100, limit or 5)
return await self._state.query_members(
self, query=query, limit=limit, user_ids=user_ids, presences=presences, cache=cache
)
async def change_voice_state(
self,
*,
channel: Optional[VocalGuildChannel],
self_mute: bool = False,
self_deaf: bool = False,
) -> None:
"""|coro|
Changes client's voice state in the guild.
.. versionadded:: 1.4
Parameters
----------
channel: Optional[:class:`VoiceChannel`]
Channel the client wants to join. Use ``None`` to disconnect.
self_mute: :class:`bool`
Indicates if the client should be self-muted.
self_deaf: :class:`bool`
Indicates if the client should be self-deafened.
"""
ws = self._state._get_websocket(self.id)
channel_id = channel.id if channel else None
await ws.voice_state(self.id, channel_id, self_mute, self_deaf)
def fetch_scheduled_events(self, *, with_users: bool = False) -> ScheduledEventIterator:
"""Retrieves an :class:`.AsyncIterator` that enables receiving scheduled
events on this guild
.. note::
This method is an API call. For general usage, consider
:attr:`scheduled_events` instead.
.. versionadded:: 2.0
Parameters
----------
with_users: Optional[:class:`bool`]
If the event should be received with :attr:`ScheduledEvent.users`
This defaults to ``False`` - the events' :attr:`~ScheduledEvent.users`
will be empty.
Raises
------
HTTPException
Getting the events failed.
Yields
------
:class:`.ScheduledEvent`
The event with users if applicable
Examples
--------
Usage ::
async for event in guild.fetch_scheduled_events():
print(event.name)
Flattening into a list ::
events = await guild.fetch_scheduled_events().flatten()
# events is now a list of ScheduledEvent...
"""
return ScheduledEventIterator(self, with_users=with_users)
def get_scheduled_event(self, event_id: int) -> Optional[ScheduledEvent]:
"""Get a scheduled event from cache by id.
.. note::
This may not return the updated users, use
:meth:`~Guild.fetch_scheduled_event` if that is desired.
Parameters
----------
event_id : int
The scheduled event id to fetch.
Returns
-------
Optional[ScheduledEvent]
The event object, if found.
"""
return self._scheduled_events.get(event_id)
async def fetch_scheduled_event(
self, event_id: int, *, with_users: bool = False
) -> ScheduledEvent:
"""|coro|
Fetch a scheduled event object.
.. note::
This is an api call, if updated users is not needed,
consisder :meth:`~Guild.get_scheduled_event`
Parameters
----------
event_id: :class:`int`
The event id to fetch
with_users: :class:`bool`
If the users should be received and cached too, by default False
Returns
-------
:class:`ScheduledEvent`
The received event object
"""
event_payload = await self._state.http.get_event(
self.id, event_id, with_user_count=with_users
)
return self._store_scheduled_event(event_payload)
async def create_scheduled_event(
self,
*,
name: str,
entity_type: ScheduledEventEntityType,
start_time: datetime.datetime,
channel: abc.GuildChannel = MISSING,
metadata: EntityMetadata = MISSING,
privacy_level: ScheduledEventPrivacyLevel = ScheduledEventPrivacyLevel.guild_only,
end_time: datetime.datetime = MISSING,
description: str = MISSING,
image: Optional[Union[bytes, Asset, Attachment, File]] = None,
reason: Optional[str] = None,
) -> ScheduledEvent:
"""|coro|
Create a new scheduled event object.
.. versionchanged:: 2.1
The ``image`` parameter now accepts :class:`File`, :class:`Attachment`, and :class:`Asset`.
Parameters
----------
channel: :class:`abc.GuildChannel`
The channel the event will happen in, if any
metadata: :class:`EntityMetadata`
The metadata for the event
name: :class:`str`
The name of the event
privacy_level: :class:`ScheduledEventPrivacyLevel`
The privacy level for the event
start_time: :class:`py:datetime.datetime`
The scheduled start time
end_time: :class:`py:datetime.datetime`
The scheduled end time
description: :class:`str`
The description for the event
entity_type: :class:`ScheduledEventEntityType`
The type of event
image: Optional[Union[:class:`bytes`, :class:`Asset`, :class:`Attachment`, :class:`File`]]
A :term:`py:bytes-like object`, :class:`File`, :class:`Attachment`, or :class:`Asset`
representing the cover image.
reason: Optional[:class:`str`]
The reason for creating this scheduled event. Shows up in the audit logs.
Returns
-------
:class:`ScheduledEvent`
The created event object.
"""
payload: Dict[str, Any] = {
"name": name,
"entity_type": entity_type.value,
"scheduled_start_time": start_time.isoformat(),
}
if channel is not MISSING:
payload["channel_id"] = channel.id
if metadata is not MISSING:
payload["entity_metadata"] = metadata.__dict__
if privacy_level is not MISSING:
payload["privacy_level"] = privacy_level.value
if end_time is not MISSING:
payload["scheduled_end_time"] = end_time.isoformat()
if description is not MISSING:
payload["description"] = description
if image is not None:
payload["image"] = await utils.obj_to_base64_data(image)
data = await self._state.http.create_event(self.id, reason=reason, **payload)
return self._store_scheduled_event(data)
def get_application_commands(self, rollout: bool = False):
"""Gets all application commands registered for this guild.
Parameters
----------
rollout: :class:`bool`
Returns
-------
"""
return self._state.get_guild_application_commands(guild_id=self.id, rollout=rollout)
def add_application_command(
self, app_cmd: BaseApplicationCommand, overwrite: bool = False, use_rollout: bool = False
) -> None:
app_cmd.add_guild_rollout(self.id)
self._state.add_application_command(app_cmd, overwrite=overwrite, use_rollout=use_rollout)
async def deploy_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
) -> None:
await self._state.discover_application_commands(
data=data,
guild_id=self.id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
async def sync_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
*,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
) -> None:
"""|coro|
Syncs the locally added application commands with this Guild.
Parameters
----------
data: Optional[List[:class:`dict`]]
Data to use when comparing local application commands to what Discord has. Should be a list of application
command data from Discord. If left as ``None``, it will be fetched if needed. Defaults to ``None``.
associate_known: :class:`bool`
If local commands that match a command already on Discord should be associated with each other.
Defaults to ``True``.
delete_unknown: :class:`bool`
If commands on Discord that don't match a local command should be deleted. Defaults to ``True``.
update_known: :class:`bool`
If commands on Discord have a basic match with a local command, but don't fully match, should be updated.
Defaults to ``True``.
register_new: :class:`bool`
If a local command that doesn't have a basic match on Discord should be added to Discord.
Defaults to ``True``.
"""
# All this does is passthrough to connection state. All documentation updates should also be updated
# there, and vice versa.
await self._state.sync_application_commands(
data=data,
guild_id=self.id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
register_new=register_new,
)
async def rollout_application_commands(
self,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
) -> None:
"""|coro|
Rolls out application commands to the guild, associating, deleting, updating, and/or newly
registering as needed.
Parameters
----------
associate_known: :class:`bool`
Whether commands on Discord that match a locally added command should be associated with each other.
Defaults to ``True``
delete_unknown
update_known
register_new
"""
warnings.warn(
".rollout_application_commands is deprecated, use .sync_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
if self._state.application_id is None:
raise NotImplementedError("Could not get the current application id")
guild_payload = await self._state.http.get_guild_commands(
self._state.application_id, self.id
)
await self.deploy_application_commands(
data=guild_payload,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
if register_new:
await self.register_new_application_commands(data=guild_payload)
async def delete_unknown_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None
) -> None:
await self._state.delete_unknown_application_commands(data=data, guild_id=self.id)
async def associate_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None
) -> None:
await self._state.associate_application_commands(data=data, guild_id=self.id)
async def update_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None
) -> None:
await self._state.update_application_commands(data=data, guild_id=self.id)
async def register_new_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None
) -> None:
await self._state.register_new_application_commands(data=data, guild_id=self.id)
async def register_application_commands(self, *commands: BaseApplicationCommand) -> None:
for command in commands:
await self._state.register_application_command(command, guild_id=self.id)
async def delete_application_commands(self, *commands: BaseApplicationCommand) -> None:
for command in commands:
await self._state.delete_application_command(command, guild_id=self.id)
async def auto_moderation_rules(self) -> List[AutoModerationRule]:
"""|coro|
Get the list of auto moderation rules from this guild.
Requires the :attr:`~Permissions.manage_guild` permission.
.. versionadded:: 2.1
Raises
------
Forbidden
You do not have permission to fetch the auto moderation rules.
Returns
-------
List[:class:`AutoModerationRule`]
The auto moderation rules of this guild.
"""
data = await self._state.http.list_guild_auto_moderation_rules(self.id)
return [AutoModerationRule(data=d, state=self._state) for d in data]
async def fetch_auto_moderation_rule(self, rule_id: int, /) -> AutoModerationRule:
"""|coro|
Retrieves a :class:`AutoModerationRule` from this guild by its ID
Requires the :attr:`~Permissions.manage_guild` permission.
.. versionadded:: 2.1
Parameters
----------
rule_id: :class:`int`
The ID of the auto moderation rule to fetch.
Raises
------
NotFound
The requested rule could not be found.
Forbidden
You do not have permission to fetch auto moderation rules.
HTTPException
Fetching the rule failed.
Returns
-------
:class:`AutoModerationRule`
The found auto moderation rule.
"""
data = await self._state.http.get_auto_moderation_rule(self.id, rule_id)
return AutoModerationRule(data=data, state=self._state)
async def create_auto_moderation_rule(
self,
*,
name: str,
event_type: AutoModerationEventType,
trigger_type: AutoModerationTriggerType,
actions: List[AutoModerationAction],
trigger_metadata: Optional[AutoModerationTriggerMetadata] = None,
enabled: Optional[bool] = None,
exempt_roles: Optional[List[Snowflake]] = None,
exempt_channels: Optional[List[Snowflake]] = None,
reason: Optional[str] = None,
) -> AutoModerationRule:
"""|coro|
Create a new auto moderation rule.
Requires the :attr:`~Permissions.manage_guild` permission.
.. versionadded:: 2.1
Parameters
----------
name: :class:`str`
The name to use for this rule.
event_type: :class:`AutoModerationEventType`
The type of event conteto listen to for this rule.
actions: List[:class:`AutoModerationAction`]
The actions to execute when this rule is triggered.
trigger_type: :class:`AutoModerationTriggerType`
The type of content that triggers this rule.
trigger_metadata: Optional[:class:`AutoModerationTriggerMetadata`]
The additional data to use to determine if this rule has been triggered.
enabled: Optional[:class:`bool`]
If this rule should be enabled.
exempt_roles: Optional[List[:class:`abc.Snowflake`]]
Roles that should be exempt from this rule.
exempt_channels: Optional[List[:class:`abc.Snowflake`]]
Channels that should be exempt from this rule.
reason: Optional[:class:`str`]
The reason for creating this rule. Shows in the audit log.
Raises
------
Forbidden
You do not have permission to create auto moderation rules.
HTTPException
Creating the rule failed.
InvalidArgument
An invalid type was passed for an argument.
Returns
-------
:class:`AutoModerationRule`
The newly created auto moderation rule.
"""
if not isinstance(event_type, AutoModerationEventType):
raise InvalidArgument("event_type must be of type AutoModerationEventType")
if not isinstance(trigger_type, AutoModerationTriggerType):
raise InvalidArgument("trigger_type must be of type AutoModerationTriggerType")
payload: AutoModerationRuleCreate = {
"name": str(name),
"event_type": event_type.value,
"trigger_type": trigger_type.value,
"actions": [action.payload for action in actions],
}
if trigger_metadata is not None:
if not isinstance(trigger_metadata, AutoModerationTriggerMetadata):
raise InvalidArgument(
"trigger_metadata must be of type AutoModerationTriggerMetadata"
)
payload["trigger_metadata"] = trigger_metadata.payload
if enabled is not None:
payload["enabled"] = enabled
if exempt_roles is not None:
payload["exempt_roles"] = [str(role.id) for role in exempt_roles]
if exempt_channels is not None:
payload["exempt_channels"] = [str(channel.id) for channel in exempt_channels]
data = await self._state.http.create_auto_moderation_rule(
self.id, data=payload, reason=reason
)
return AutoModerationRule(data=data, state=self._state)
def parse_mentions(self, text: str) -> List[Union[Member, User]]:
"""Parses user mentions in a string and returns a list of :class:`Member` objects.
If the member is not in the guild, a :class:`User` object is returned for that member instead.
.. note::
This does not include role or channel mentions. See :meth:`~Guild.parse_role_mentions`
for :class:`Role` objects and :meth:`~Guild.parse_channel_mentions` for
:class:`~abc.GuildChannel` objects.
.. note::
Only members or users found in the cache will be returned. To get the IDs of all users
mentioned, use :func:`~utils.parse_raw_mentions` instead.
.. versionadded:: 2.2
Parameters
----------
text: :class:`str`
String to parse mentions in.
Returns
-------
List[Union[:class:`Member`, :class:`User`]]
List of :class:`Member` or :class:`User` objects that were mentioned in the string.
"""
get_member_or_user: Callable[
[int], Optional[Union[Member, User]]
] = lambda id: self.get_member(id) or self._state.get_user(id)
it = filter(None, map(get_member_or_user, utils.parse_raw_mentions(text)))
return utils.unique(it)
def parse_role_mentions(self, text: str) -> List[Role]:
"""Parses role mentions in a string and returns a list of :class:`Role` objects.
.. note::
Only cached roles found in the :class:`Guild` will be returned. To get the IDs
of all roles mentioned, use :func:`~utils.parse_raw_role_mentions` instead.
.. versionadded:: 2.2
Parameters
----------
text: :class:`str`
String to parse mentions in.
Returns
-------
List[:class:`Role`]
List of :class:`Role` objects that were mentioned in the string.
"""
it = filter(None, map(self.get_role, utils.parse_raw_role_mentions(text)))
return utils.unique(it)
def parse_channel_mentions(self, text: str) -> List[abc.GuildChannel]:
"""Parses channel mentions in a string and returns a list of :class:`~abc.GuildChannel` objects.
.. note::
Only cached channels found in the :class:`Guild` will be returned. To get the IDs of all
channels mentioned, use :func:`~utils.parse_raw_channel_mentions` instead.
.. versionadded:: 2.2
Parameters
----------
text: :class:`str`
String to parse mentions in.
Returns
-------
List[:class:`~abc.GuildChannel`]
List of :class:`~abc.GuildChannel` objects that were mentioned in the string.
"""
it = filter(None, map(self.get_channel, utils.parse_raw_channel_mentions(text)))
return utils.unique(it)
Snowflake = Union[str, int]
def _transform_guild_id(entry: AuditLogEntry, data: Optional[Snowflake]) -> Optional[Guild]:
if data is None:
return None
return entry._state._get_guild(int(data)) | null |
161,003 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
r"""Represents an Audit Log entry.
You retrieve these via :meth:`Guild.audit_logs`.
.. container:: operations
.. describe:: x == y
Checks if two entries are equal.
.. describe:: x != y
Checks if two entries are not equal.
.. describe:: hash(x)
Returns the entry's hash.
.. versionchanged:: 1.7
Audit log entries are now comparable and hashable.
Attributes
----------
action: :class:`AuditLogAction`
The action that was done.
user: :class:`abc.User`
The user who initiated this action. Usually a :class:`Member`\, unless gone
then it's a :class:`User`.
id: :class:`int`
The entry ID.
target: Any
The target that got changed. The exact type of this depends on
the action being done.
reason: Optional[:class:`str`]
The reason this action was done.
extra: Any
Extra information that this entry has that might be useful.
For most actions, this is ``None``. However in some cases it
contains extra information. See :class:`AuditLogAction` for
which actions have this field filled out.
"""
extra: Union[
_AuditLogProxyMemberPrune,
_AuditLogProxyMemberMoveOrMessageDelete,
_AuditLogProxyMemberDisconnect,
_AuditLogProxyPinAction,
_AuditLogProxyStageInstanceAction,
_AuditLogProxyAutoModerationBlockMessage,
Member,
User,
None,
Role,
]
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
self._state = guild._state
self.guild = guild
self._auto_moderation_rules = auto_moderation_rules
self._users = users
self._from_data(data)
def _from_data(self, data: AuditLogEntryPayload) -> None:
self.action = enums.try_enum(enums.AuditLogAction, data["action_type"])
self.id = int(data["id"])
# this key is technically not usually present
self.reason = data.get("reason")
self.extra = data.get("options", {}) # type: ignore
# I gave up trying to fix this
elems: Dict[str, Any] = {}
channel_id = int(self.extra["channel_id"]) if self.extra.get("channel_id", None) else None
if isinstance(self.action, enums.AuditLogAction) and self.extra:
if self.action is enums.AuditLogAction.member_prune:
# member prune has two keys with useful information
self.extra = type( # type: ignore
"_AuditLogProxy", (), {k: int(v) for k, v in self.extra.items()} # type: ignore
)()
elif (
self.action is enums.AuditLogAction.member_move
or self.action is enums.AuditLogAction.message_delete
):
elems = {
"count": int(self.extra["count"]),
}
elif self.action is enums.AuditLogAction.member_disconnect:
# The member disconnect action has a dict with some information
elems = {
"count": int(self.extra["count"]),
}
elif self.action.name.endswith("pin"):
# the pin actions have a dict with some information
elems = {
"message_id": int(self.extra["message_id"]),
}
elif self.action.name.startswith("overwrite_"):
# the overwrite_ actions have a dict with some information
instance_id = int(self.extra["id"])
the_type = self.extra.get("type")
if the_type == "1":
self.extra = self._get_member(instance_id)
elif the_type == "0":
role = self.guild.get_role(instance_id)
if role is None:
role = Object(id=instance_id)
role.name = self.extra.get("role_name") # type: ignore
self.extra = role # type: ignore
elif self.action.name.startswith("stage_instance"):
channel_id = int(self.extra["channel_id"])
elems = {"channel": self.guild.get_channel(channel_id) or Object(id=channel_id)}
elif (
self.action is enums.AuditLogAction.auto_moderation_block_message
or self.action is enums.AuditLogAction.auto_moderation_flag_to_channel
or self.action is enums.AuditLogAction.auto_moderation_user_communication_disabled
):
elems = {
"rule_name": self.extra["auto_moderation_rule_name"],
"rule_trigger_type": enums.try_enum(
enums.AutoModerationTriggerType,
int(self.extra["auto_moderation_rule_trigger_type"]),
),
}
# this just gets automatically filled in if present, this way prevents crashes if channel_id is None
if channel_id and self.action:
elems["channel"] = self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id)
if type(self.extra) is dict:
self.extra = type("_AuditLogProxy", (), elems)() # type: ignore
# this key is not present when the above is present, typically.
# It's a list of { new_value: a, old_value: b, key: c }
# where new_value and old_value are not guaranteed to be there depending
# on the action type, so let's just fetch it for now and only turn it
# into meaningful data when requested
self._changes = data.get("changes", [])
self.user = self._get_member(utils.get_as_snowflake(data, "user_id")) # type: ignore
self._target_id = utils.get_as_snowflake(data, "target_id")
def _get_member(self, user_id: int) -> Union[Member, User, None]:
return self.guild.get_member(user_id) or self._users.get(user_id)
def __repr__(self) -> str:
return f"<AuditLogEntry id={self.id} action={self.action} user={self.user!r}>"
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the entry's creation time in UTC."""
return utils.snowflake_time(self.id)
def target(self) -> AuditTarget:
try:
converter = getattr(self, "_convert_target_" + str(self.action.target_type))
except AttributeError:
if self._target_id is None:
return None
return Object(id=self._target_id)
else:
return converter(self._target_id)
def category(self) -> Optional[enums.AuditLogActionCategory]:
"""Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable."""
return self.action.category
def changes(self) -> AuditLogChanges:
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj
def before(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's prior state."""
return self.changes.before
def after(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's subsequent state."""
return self.changes.after
def _convert_target_guild(self, target_id: int) -> Guild:
return self.guild
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
return self.guild.get_channel(target_id) or Object(id=target_id)
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
return self.guild.get_role(target_id) or Object(id=target_id)
def _convert_target_invite(self, target_id: int) -> Invite:
# invites have target_id set to null
# so figure out which change has the full invite data
changeset = self.before if self.action is enums.AuditLogAction.invite_delete else self.after
fake_payload = {
"max_age": changeset.max_age,
"max_uses": changeset.max_uses,
"code": changeset.code,
"temporary": changeset.temporary,
"uses": changeset.uses,
}
obj = Invite(state=self._state, data=fake_payload, guild=self.guild, channel=changeset.channel) # type: ignore
with contextlib.suppress(AttributeError):
obj.inviter = changeset.inviter
return obj
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
return self._state.get_emoji(target_id) or Object(id=target_id)
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
return self.guild.get_stage_instance(target_id) or Object(id=target_id)
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
return self._state.get_sticker(target_id) or Object(id=target_id)
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
return self.guild.get_thread(target_id) or Object(id=target_id)
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
return self._auto_moderation_rules.get(rule_id) or Object(id=rule_id)
class Object(Hashable):
"""Represents a generic Discord object.
The purpose of this class is to allow you to create 'miniature'
versions of data classes if you want to pass in just an ID. Most functions
that take in a specific data class with an ID can also take in this class
as a substitute instead. Note that even though this is the case, not all
objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received
in :dpyissue:`strange order <21>` and when such events happened you would
receive this class rather than the actual data class. These cases are
extremely rare.
.. container:: operations
.. describe:: x == y
Checks if two objects are equal.
.. describe:: x != y
Checks if two objects are not equal.
.. describe:: hash(x)
Returns the object's hash.
Attributes
----------
id: :class:`int`
The ID of the object.
"""
def __init__(self, id: SupportsIntCast) -> None:
try:
id = int(id)
except ValueError:
raise TypeError(
f"id parameter must be convertable to int not {id.__class__!r}"
) from None
else:
self.id = id
def __repr__(self) -> str:
return f"<Object id={self.id!r}>"
def __int__(self) -> int:
return self.id
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the snowflake's creation time in UTC."""
return utils.snowflake_time(self.id)
class Permissions(BaseFlags):
"""Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual
bits using the properties as if they were regular bools. This allows
you to edit permissions.
.. versionchanged:: 1.3
You can now use keyword arguments to initialize :class:`Permissions`
similar to :meth:`update`.
.. container:: operations
.. describe:: x == y
Checks if two permissions are equal.
.. describe:: x != y
Checks if two permissions are not equal.
.. describe:: x <= y
Checks if a permission is a subset of another permission.
.. describe:: x >= y
Checks if a permission is a superset of another permission.
.. describe:: x < y
Checks if a permission is a strict subset of another permission.
.. describe:: x > y
Checks if a permission is a strict superset of another permission.
.. describe:: hash(x)
Return the permission's hash.
.. describe:: iter(x)
Returns an iterator of ``(perm, value)`` pairs. This allows it
to be, for example, constructed as a dict or a list of pairs.
Note that aliases are not shown.
Attributes
----------
value: :class:`int`
The raw value. This value is a bit array field of a 53-bit integer
representing the currently available permissions. You should query
permissions via the properties rather than using this raw value.
"""
__slots__ = ()
def __init__(self, permissions: int = 0, **kwargs: bool) -> None:
if not isinstance(permissions, int):
raise TypeError(
f"Expected int parameter, received {permissions.__class__.__name__} instead."
)
self.value = permissions
for key, value in kwargs.items():
if key not in self.VALID_FLAGS:
raise TypeError(f"{key!r} is not a valid permission name.")
setattr(self, key, value)
def is_subset(self, other: Permissions) -> bool:
"""Returns ``True`` if self has the same or fewer permissions as other."""
if isinstance(other, Permissions):
return (self.value & other.value) == self.value
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}")
def is_superset(self, other: Permissions) -> bool:
"""Returns ``True`` if self has the same or more permissions as other."""
if isinstance(other, Permissions):
return (self.value | other.value) == self.value
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}")
def is_strict_subset(self, other: Permissions) -> bool:
"""Returns ``True`` if the permissions on other are a strict subset of those on self."""
return self.is_subset(other) and self != other
def is_strict_superset(self, other: Permissions) -> bool:
"""Returns ``True`` if the permissions on other are a strict superset of those on self."""
return self.is_superset(other) and self != other
__le__ = is_subset
__ge__ = is_superset
__lt__ = is_strict_subset
__gt__ = is_strict_superset
def none(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
permissions set to ``False``."""
return cls(0)
def all(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
permissions set to ``True``.
"""
return cls(-1)
def all_channel(cls) -> Self:
"""A :class:`Permissions` with all channel-specific permissions set to
``True`` and the guild-specific ones set to ``False``. The guild-specific
permissions are currently:
- :attr:`manage_emojis`
- :attr:`view_audit_log`
- :attr:`view_guild_insights`
- :attr:`manage_guild`
- :attr:`change_nickname`
- :attr:`manage_nicknames`
- :attr:`kick_members`
- :attr:`ban_members`
- :attr:`administrator`
.. versionchanged:: 1.7
Added :attr:`stream`, :attr:`priority_speaker` and :attr:`use_slash_commands` permissions.
.. versionchanged:: 2.0
Added :attr:`create_public_threads`, :attr:`create_private_threads`, :attr:`manage_threads`,
:attr:`use_external_stickers`, :attr:`send_messages_in_threads` and
:attr:`request_to_speak` permissions.
"""
return cls(0b111110110110011111101111111111101010001)
def general(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"General" permissions from the official Discord UI set to ``True``.
.. versionchanged:: 1.7
Permission :attr:`read_messages` is now included in the general permissions, but
permissions :attr:`administrator`, :attr:`create_instant_invite`, :attr:`kick_members`,
:attr:`ban_members`, :attr:`change_nickname` and :attr:`manage_nicknames` are
no longer part of the general permissions.
"""
return cls(0b01110000000010000000010010110000)
def membership(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Membership" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(0b00001100000000000000000000000111)
def text(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Text" permissions from the official Discord UI set to ``True``.
.. versionchanged:: 1.7
Permission :attr:`read_messages` is no longer part of the text permissions.
Added :attr:`use_slash_commands` permission.
.. versionchanged:: 2.0
Added :attr:`create_public_threads`, :attr:`create_private_threads`, :attr:`manage_threads`,
:attr:`send_messages_in_threads` and :attr:`use_external_stickers` permissions.
"""
return cls(0b111110010000000000001111111100001000000)
def voice(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Voice" permissions from the official Discord UI set to ``True``."""
return cls(0b00000011111100000000001100000000)
def stage(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Stage Channel" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(1 << 32)
def stage_moderator(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Stage Moderator" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(0b100000001010000000000000000000000)
def advanced(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Advanced" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(1 << 3)
def update(self, **kwargs: bool) -> None:
r"""Bulk updates this permission object.
Allows you to set multiple attributes by using keyword
arguments. The names must be equivalent to the properties
listed. Extraneous key/value pairs will be silently ignored.
Parameters
----------
\*\*kwargs
A list of key/value pairs to bulk update permissions with.
"""
for key, value in kwargs.items():
if key in self.VALID_FLAGS:
setattr(self, key, value)
def handle_overwrite(self, allow: int, deny: int) -> None:
# Basically this is what's happening here.
# We have an original bit array, e.g. 1010
# Then we have another bit array that is 'denied', e.g. 1111
# And then we have the last one which is 'allowed', e.g. 0101
# We want original OP denied to end up resulting in
# whatever is in denied to be set to 0.
# So 1010 OP 1111 -> 0000
# Then we take this value and look at the allowed values.
# And whatever is allowed is set to 1.
# So 0000 OP2 0101 -> 0101
# The OP is base & ~denied.
# The OP2 is base | allowed.
self.value = (self.value & ~deny) | allow
def create_instant_invite(self) -> int:
""":class:`bool`: Returns ``True`` if the user can create instant invites."""
return 1 << 0
def kick_members(self) -> int:
""":class:`bool`: Returns ``True`` if the user can kick users from the guild."""
return 1 << 1
def ban_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can ban users from the guild."""
return 1 << 2
def administrator(self) -> int:
""":class:`bool`: Returns ``True`` if a user is an administrator. This role overrides all other permissions.
This also bypasses all channel-specific overrides.
"""
return 1 << 3
def manage_channels(self) -> int:
""":class:`bool`: Returns ``True`` if a user can edit, delete, or create channels in the guild.
This also corresponds to the "Manage Channel" channel-specific override."""
return 1 << 4
def manage_guild(self) -> int:
""":class:`bool`: Returns ``True`` if a user can edit guild properties."""
return 1 << 5
def add_reactions(self) -> int:
""":class:`bool`: Returns ``True`` if a user can add reactions to messages."""
return 1 << 6
def view_audit_log(self) -> int:
""":class:`bool`: Returns ``True`` if a user can view the guild's audit log."""
return 1 << 7
def priority_speaker(self) -> int:
""":class:`bool`: Returns ``True`` if a user can be more easily heard while talking."""
return 1 << 8
def stream(self) -> int:
""":class:`bool`: Returns ``True`` if a user can stream in a voice channel."""
return 1 << 9
def read_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can read messages from all or specific text channels."""
return 1 << 10
def view_channel(self) -> int:
""":class:`bool`: An alias for :attr:`read_messages`.
.. versionadded:: 1.3
"""
return 1 << 10
def send_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send messages from all or specific text channels.
This falls under ``Create Posts`` on the UI specifically for Forum Channels.
"""
return 1 << 11
def send_tts_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send TTS messages from all or specific text channels."""
return 1 << 12
def manage_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can delete or pin messages in a text channel.
.. note::
Note that there are currently no ways to edit other people's messages.
"""
return 1 << 13
def embed_links(self) -> int:
""":class:`bool`: Returns ``True`` if a user's messages will automatically be embedded by Discord."""
return 1 << 14
def attach_files(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send files in their messages."""
return 1 << 15
def read_message_history(self) -> int:
""":class:`bool`: Returns ``True`` if a user can read a text channel's previous messages."""
return 1 << 16
def mention_everyone(self) -> int:
""":class:`bool`: Returns ``True`` if a user's @everyone or @here will mention everyone in the text channel."""
return 1 << 17
def external_emojis(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use emojis from other guilds."""
return 1 << 18
def use_external_emojis(self) -> int:
""":class:`bool`: An alias for :attr:`external_emojis`.
.. versionadded:: 1.3
"""
return 1 << 18
def view_guild_insights(self) -> int:
""":class:`bool`: Returns ``True`` if a user can view the guild's insights.
.. versionadded:: 1.3
"""
return 1 << 19
def connect(self) -> int:
""":class:`bool`: Returns ``True`` if a user can connect to a voice channel."""
return 1 << 20
def speak(self) -> int:
""":class:`bool`: Returns ``True`` if a user can speak in a voice channel."""
return 1 << 21
def mute_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can mute other users."""
return 1 << 22
def deafen_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can deafen other users."""
return 1 << 23
def move_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can move users between other voice channels."""
return 1 << 24
def use_voice_activation(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use voice activation in voice channels."""
return 1 << 25
def change_nickname(self) -> int:
""":class:`bool`: Returns ``True`` if a user can change their nickname in the guild."""
return 1 << 26
def manage_nicknames(self) -> int:
""":class:`bool`: Returns ``True`` if a user can change other user's nickname in the guild."""
return 1 << 27
def manage_roles(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create or edit roles less than their role's position.
This also corresponds to the "Manage Permissions" channel-specific override.
"""
return 1 << 28
def manage_permissions(self) -> int:
""":class:`bool`: An alias for :attr:`manage_roles`.
.. versionadded:: 1.3
"""
return 1 << 28
def manage_webhooks(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create, edit, or delete webhooks."""
return 1 << 29
def manage_emojis(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create, edit, or delete emojis."""
return 1 << 30
def manage_emojis_and_stickers(self) -> int:
""":class:`bool`: An alias for :attr:`manage_emojis`.
.. versionadded:: 2.0
"""
return 1 << 30
def use_slash_commands(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use slash commands.
.. versionadded:: 1.7
"""
return 1 << 31
def request_to_speak(self) -> int:
""":class:`bool`: Returns ``True`` if a user can request to speak in a stage channel.
.. versionadded:: 1.7
"""
return 1 << 32
def manage_events(self) -> int:
""":class:`bool`: Returns ``True`` if a user can manage guild events.
.. versionadded:: 2.0
"""
return 1 << 33
def manage_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can manage threads.
.. versionadded:: 2.0
"""
return 1 << 34
def create_public_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create public threads.
.. versionadded:: 2.0
"""
return 1 << 35
def create_private_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create private threads.
.. versionadded:: 2.0
"""
return 1 << 36
def external_stickers(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use stickers from other guilds.
.. versionadded:: 2.0
"""
return 1 << 37
def use_external_stickers(self) -> int:
""":class:`bool`: An alias for :attr:`external_stickers`.
.. versionadded:: 2.0
"""
return 1 << 37
def send_messages_in_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send messages in threads.
This falls under ``Send Messages in Posts`` on the UI specifically for Forum channels.
.. versionadded:: 2.0
"""
return 1 << 38
def start_embedded_activities(self) -> int:
""":class:`bool`: Returns ``True`` if a user can launch activities in a voice channel.
.. versionadded:: 2.0
"""
return 1 << 39
def moderate_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can moderate members (add timeouts).
Referred to as ``Timeout Members`` in the discord client.
.. versionadded:: 2.0
"""
return 1 << 40
class PermissionOverwrite:
r"""A type that is used to represent a channel specific permission.
Unlike a regular :class:`Permissions`\, the default value of a
permission is equivalent to ``None`` and not ``False``. Setting
a value to ``False`` is **explicitly** denying that permission,
while setting a value to ``True`` is **explicitly** allowing
that permission.
The values supported by this are the same as :class:`Permissions`
with the added possibility of it being set to ``None``.
.. container:: operations
.. describe:: x == y
Checks if two overwrites are equal.
.. describe:: x != y
Checks if two overwrites are not equal.
.. describe:: iter(x)
Returns an iterator of ``(perm, value)`` pairs. This allows it
to be, for example, constructed as a dict or a list of pairs.
Note that aliases are not shown.
Parameters
----------
\*\*kwargs
Set the value of permissions by their name.
"""
__slots__ = ("_values",)
if TYPE_CHECKING:
VALID_NAMES: ClassVar[Set[str]]
PURE_FLAGS: ClassVar[Set[str]]
# I wish I didn't have to do this
create_instant_invite: Optional[bool]
kick_members: Optional[bool]
ban_members: Optional[bool]
administrator: Optional[bool]
manage_channels: Optional[bool]
manage_guild: Optional[bool]
add_reactions: Optional[bool]
view_audit_log: Optional[bool]
priority_speaker: Optional[bool]
stream: Optional[bool]
read_messages: Optional[bool]
view_channel: Optional[bool]
send_messages: Optional[bool]
send_tts_messages: Optional[bool]
manage_messages: Optional[bool]
embed_links: Optional[bool]
attach_files: Optional[bool]
read_message_history: Optional[bool]
mention_everyone: Optional[bool]
external_emojis: Optional[bool]
use_external_emojis: Optional[bool]
view_guild_insights: Optional[bool]
connect: Optional[bool]
speak: Optional[bool]
mute_members: Optional[bool]
deafen_members: Optional[bool]
move_members: Optional[bool]
use_voice_activation: Optional[bool]
change_nickname: Optional[bool]
manage_nicknames: Optional[bool]
manage_roles: Optional[bool]
manage_permissions: Optional[bool]
manage_webhooks: Optional[bool]
manage_emojis: Optional[bool]
manage_emojis_and_stickers: Optional[bool]
use_slash_commands: Optional[bool]
request_to_speak: Optional[bool]
manage_events: Optional[bool]
manage_threads: Optional[bool]
create_public_threads: Optional[bool]
create_private_threads: Optional[bool]
send_messages_in_threads: Optional[bool]
external_stickers: Optional[bool]
use_external_stickers: Optional[bool]
start_embedded_activities: Optional[bool]
moderate_members: Optional[bool]
def __init__(self, **kwargs: Optional[bool]) -> None:
self._values: Dict[str, Optional[bool]] = {}
for key, value in kwargs.items():
if key not in self.VALID_NAMES:
raise ValueError(f"No permission called {key}.")
setattr(self, key, value)
def __eq__(self, other: Any) -> bool:
return isinstance(other, PermissionOverwrite) and self._values == other._values
def _set(self, key: str, value: Optional[bool]) -> None:
if value not in (True, None, False):
raise TypeError(f"Expected bool or NoneType, received {value.__class__.__name__}")
if value is None:
self._values.pop(key, None)
else:
self._values[key] = value
def pair(self) -> Tuple[Permissions, Permissions]:
"""Tuple[:class:`Permissions`, :class:`Permissions`]: Returns the (allow, deny) pair from this overwrite."""
allow = Permissions.none()
deny = Permissions.none()
for key, value in self._values.items():
if value is True:
setattr(allow, key, True)
elif value is False:
setattr(deny, key, True)
return allow, deny
def from_pair(cls, allow: Permissions, deny: Permissions) -> Self:
"""Creates an overwrite from an allow/deny pair of :class:`Permissions`."""
ret = cls()
for key, value in allow:
if value is True:
setattr(ret, key, True)
for key, value in deny:
if value is True:
setattr(ret, key, False)
return ret
def is_empty(self) -> bool:
"""Checks if the permission overwrite is currently empty.
An empty permission overwrite is one that has no overwrites set
to ``True`` or ``False``.
Returns
-------
:class:`bool`
Indicates if the overwrite is empty.
"""
return len(self._values) == 0
def update(self, **kwargs: bool) -> None:
r"""Bulk updates this permission overwrite object.
Allows you to set multiple attributes by using keyword
arguments. The names must be equivalent to the properties
listed. Extraneous key/value pairs will be silently ignored.
Parameters
----------
\*\*kwargs
A list of key/value pairs to bulk update with.
"""
for key, value in kwargs.items():
if key not in self.VALID_NAMES:
continue
setattr(self, key, value)
def __iter__(self) -> Iterator[Tuple[str, Optional[bool]]]:
for key in self.PURE_FLAGS:
yield key, self._values.get(key)
class PermissionOverwrite(TypedDict):
id: Snowflake
type: OverwriteType
allow: str
deny: str
def _transform_overwrites(
entry: AuditLogEntry, data: List[PermissionOverwritePayload]
) -> List[Tuple[Object, PermissionOverwrite]]:
overwrites = []
for elem in data:
allow = Permissions(int(elem["allow"]))
deny = Permissions(int(elem["deny"]))
ow = PermissionOverwrite.from_pair(allow, deny)
ow_type = elem["type"]
ow_id = int(elem["id"])
target = None
if str(ow_type) == "0":
target = entry.guild.get_role(ow_id)
elif str(ow_type) == "1":
target = entry._get_member(ow_id)
if target is None:
target = Object(id=ow_id)
overwrites.append((target, ow))
return overwrites | null |
161,004 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
r"""Represents an Audit Log entry.
You retrieve these via :meth:`Guild.audit_logs`.
.. container:: operations
.. describe:: x == y
Checks if two entries are equal.
.. describe:: x != y
Checks if two entries are not equal.
.. describe:: hash(x)
Returns the entry's hash.
.. versionchanged:: 1.7
Audit log entries are now comparable and hashable.
Attributes
----------
action: :class:`AuditLogAction`
The action that was done.
user: :class:`abc.User`
The user who initiated this action. Usually a :class:`Member`\, unless gone
then it's a :class:`User`.
id: :class:`int`
The entry ID.
target: Any
The target that got changed. The exact type of this depends on
the action being done.
reason: Optional[:class:`str`]
The reason this action was done.
extra: Any
Extra information that this entry has that might be useful.
For most actions, this is ``None``. However in some cases it
contains extra information. See :class:`AuditLogAction` for
which actions have this field filled out.
"""
extra: Union[
_AuditLogProxyMemberPrune,
_AuditLogProxyMemberMoveOrMessageDelete,
_AuditLogProxyMemberDisconnect,
_AuditLogProxyPinAction,
_AuditLogProxyStageInstanceAction,
_AuditLogProxyAutoModerationBlockMessage,
Member,
User,
None,
Role,
]
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
self._state = guild._state
self.guild = guild
self._auto_moderation_rules = auto_moderation_rules
self._users = users
self._from_data(data)
def _from_data(self, data: AuditLogEntryPayload) -> None:
self.action = enums.try_enum(enums.AuditLogAction, data["action_type"])
self.id = int(data["id"])
# this key is technically not usually present
self.reason = data.get("reason")
self.extra = data.get("options", {}) # type: ignore
# I gave up trying to fix this
elems: Dict[str, Any] = {}
channel_id = int(self.extra["channel_id"]) if self.extra.get("channel_id", None) else None
if isinstance(self.action, enums.AuditLogAction) and self.extra:
if self.action is enums.AuditLogAction.member_prune:
# member prune has two keys with useful information
self.extra = type( # type: ignore
"_AuditLogProxy", (), {k: int(v) for k, v in self.extra.items()} # type: ignore
)()
elif (
self.action is enums.AuditLogAction.member_move
or self.action is enums.AuditLogAction.message_delete
):
elems = {
"count": int(self.extra["count"]),
}
elif self.action is enums.AuditLogAction.member_disconnect:
# The member disconnect action has a dict with some information
elems = {
"count": int(self.extra["count"]),
}
elif self.action.name.endswith("pin"):
# the pin actions have a dict with some information
elems = {
"message_id": int(self.extra["message_id"]),
}
elif self.action.name.startswith("overwrite_"):
# the overwrite_ actions have a dict with some information
instance_id = int(self.extra["id"])
the_type = self.extra.get("type")
if the_type == "1":
self.extra = self._get_member(instance_id)
elif the_type == "0":
role = self.guild.get_role(instance_id)
if role is None:
role = Object(id=instance_id)
role.name = self.extra.get("role_name") # type: ignore
self.extra = role # type: ignore
elif self.action.name.startswith("stage_instance"):
channel_id = int(self.extra["channel_id"])
elems = {"channel": self.guild.get_channel(channel_id) or Object(id=channel_id)}
elif (
self.action is enums.AuditLogAction.auto_moderation_block_message
or self.action is enums.AuditLogAction.auto_moderation_flag_to_channel
or self.action is enums.AuditLogAction.auto_moderation_user_communication_disabled
):
elems = {
"rule_name": self.extra["auto_moderation_rule_name"],
"rule_trigger_type": enums.try_enum(
enums.AutoModerationTriggerType,
int(self.extra["auto_moderation_rule_trigger_type"]),
),
}
# this just gets automatically filled in if present, this way prevents crashes if channel_id is None
if channel_id and self.action:
elems["channel"] = self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id)
if type(self.extra) is dict:
self.extra = type("_AuditLogProxy", (), elems)() # type: ignore
# this key is not present when the above is present, typically.
# It's a list of { new_value: a, old_value: b, key: c }
# where new_value and old_value are not guaranteed to be there depending
# on the action type, so let's just fetch it for now and only turn it
# into meaningful data when requested
self._changes = data.get("changes", [])
self.user = self._get_member(utils.get_as_snowflake(data, "user_id")) # type: ignore
self._target_id = utils.get_as_snowflake(data, "target_id")
def _get_member(self, user_id: int) -> Union[Member, User, None]:
return self.guild.get_member(user_id) or self._users.get(user_id)
def __repr__(self) -> str:
return f"<AuditLogEntry id={self.id} action={self.action} user={self.user!r}>"
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the entry's creation time in UTC."""
return utils.snowflake_time(self.id)
def target(self) -> AuditTarget:
try:
converter = getattr(self, "_convert_target_" + str(self.action.target_type))
except AttributeError:
if self._target_id is None:
return None
return Object(id=self._target_id)
else:
return converter(self._target_id)
def category(self) -> Optional[enums.AuditLogActionCategory]:
"""Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable."""
return self.action.category
def changes(self) -> AuditLogChanges:
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj
def before(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's prior state."""
return self.changes.before
def after(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's subsequent state."""
return self.changes.after
def _convert_target_guild(self, target_id: int) -> Guild:
return self.guild
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
return self.guild.get_channel(target_id) or Object(id=target_id)
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
return self.guild.get_role(target_id) or Object(id=target_id)
def _convert_target_invite(self, target_id: int) -> Invite:
# invites have target_id set to null
# so figure out which change has the full invite data
changeset = self.before if self.action is enums.AuditLogAction.invite_delete else self.after
fake_payload = {
"max_age": changeset.max_age,
"max_uses": changeset.max_uses,
"code": changeset.code,
"temporary": changeset.temporary,
"uses": changeset.uses,
}
obj = Invite(state=self._state, data=fake_payload, guild=self.guild, channel=changeset.channel) # type: ignore
with contextlib.suppress(AttributeError):
obj.inviter = changeset.inviter
return obj
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
return self._state.get_emoji(target_id) or Object(id=target_id)
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
return self.guild.get_stage_instance(target_id) or Object(id=target_id)
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
return self._state.get_sticker(target_id) or Object(id=target_id)
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
return self.guild.get_thread(target_id) or Object(id=target_id)
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
return self._auto_moderation_rules.get(rule_id) or Object(id=rule_id)
class Asset(AssetMixin):
"""Represents a CDN asset on Discord.
.. container:: operations
.. describe:: str(x)
Returns the URL of the CDN asset.
.. describe:: len(x)
Returns the length of the CDN asset's URL.
.. describe:: x == y
Checks if the asset is equal to another asset.
.. describe:: x != y
Checks if the asset is not equal to another asset.
.. describe:: hash(x)
Returns the hash of the asset.
"""
__slots__: Tuple[str, ...] = (
"_state",
"_url",
"_animated",
"_key",
)
BASE = "https://cdn.discordapp.com"
def __init__(self, state, *, url: str, key: str, animated: bool = False) -> None:
self._state = state
self._url = url
self._animated = animated
self._key = key
def _from_default_avatar(cls, state, index: int) -> Asset:
return cls(
state,
url=f"{cls.BASE}/embed/avatars/{index}.png",
key=str(index),
animated=False,
)
def _from_avatar(cls, state, user_id: int, avatar: str) -> Asset:
animated = avatar.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/avatars/{user_id}/{avatar}.{format}?size=1024",
key=avatar,
animated=animated,
)
def _from_guild_avatar(cls, state, guild_id: int, member_id: int, avatar: str) -> Asset:
animated = avatar.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/guilds/{guild_id}/users/{member_id}/avatars/{avatar}.{format}?size=1024",
key=avatar,
animated=animated,
)
def _from_icon(cls, state, object_id: int, icon_hash: str, path: str) -> Asset:
return cls(
state,
url=f"{cls.BASE}/{path}-icons/{object_id}/{icon_hash}.png?size=1024",
key=icon_hash,
animated=False,
)
def _from_cover_image(cls, state, object_id: int, cover_image_hash: str) -> Asset:
return cls(
state,
url=f"{cls.BASE}/app-assets/{object_id}/store/{cover_image_hash}.png?size=1024",
key=cover_image_hash,
animated=False,
)
def _from_guild_image(cls, state, guild_id: int, image: str, path: str) -> Asset:
animated = False
format = "png"
if path == "banners":
animated = image.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/{path}/{guild_id}/{image}.{format}?size=1024",
key=image,
animated=animated,
)
def _from_guild_icon(cls, state, guild_id: int, icon_hash: str) -> Asset:
animated = icon_hash.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/icons/{guild_id}/{icon_hash}.{format}?size=1024",
key=icon_hash,
animated=animated,
)
def _from_sticker_banner(cls, state, banner: int) -> Asset:
return cls(
state,
url=f"{cls.BASE}/app-assets/710982414301790216/store/{banner}.png",
key=str(banner),
animated=False,
)
def _from_user_banner(cls, state, user_id: int, banner_hash: str) -> Asset:
animated = banner_hash.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/banners/{user_id}/{banner_hash}.{format}?size=512",
key=banner_hash,
animated=animated,
)
def _from_scheduled_event_image(cls, state, event_id: int, image_hash: str) -> Asset:
return cls(
state,
url=f"{cls.BASE}/guild-events/{event_id}/{image_hash}.png",
key=image_hash,
animated=False,
)
def __str__(self) -> str:
return self._url
def __len__(self) -> int:
return len(self._url)
def __repr__(self) -> str:
shorten = self._url.replace(self.BASE, "")
return f"<Asset url={shorten!r}>"
def __eq__(self, other):
return isinstance(other, Asset) and self._url == other._url
def __hash__(self):
return hash(self._url)
def url(self) -> str:
""":class:`str`: Returns the underlying URL of the asset."""
return self._url
def key(self) -> str:
""":class:`str`: Returns the identifying key of the asset."""
return self._key
def is_animated(self) -> bool:
""":class:`bool`: Returns whether the asset is animated."""
return self._animated
def replace(
self,
*,
size: int = MISSING,
format: ValidAssetFormatTypes = MISSING,
static_format: ValidStaticFormatTypes = MISSING,
) -> Asset:
"""Returns a new asset with the passed components replaced.
Parameters
----------
size: :class:`int`
The new size of the asset.
format: :class:`str`
The new format to change it to. Must be either
'webp', 'jpeg', 'jpg', 'png', or 'gif' if it's animated.
static_format: :class:`str`
The new format to change it to if the asset isn't animated.
Must be either 'webp', 'jpeg', 'jpg', or 'png'.
Raises
------
InvalidArgument
An invalid size or format was passed.
Returns
-------
:class:`Asset`
The newly updated asset.
"""
url = yarl.URL(self._url)
path, _ = os.path.splitext(url.path)
if format is not MISSING:
if self._animated:
if format not in VALID_ASSET_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_ASSET_FORMATS}")
url = url.with_path(f"{path}.{format}")
elif static_format is MISSING:
if format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_STATIC_FORMATS}")
url = url.with_path(f"{path}.{format}")
if static_format is not MISSING and not self._animated:
if static_format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f"static_format must be one of {VALID_STATIC_FORMATS}")
url = url.with_path(f"{path}.{static_format}")
if size is not MISSING:
if not utils.valid_icon_size(size):
raise InvalidArgument("size must be a power of 2 between 16 and 4096")
url = url.with_query(size=size)
else:
url = url.with_query(url.raw_query_string)
url = str(url)
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
def with_size(self, size: int, /) -> Asset:
"""Returns a new asset with the specified size.
Parameters
----------
size: :class:`int`
The new size of the asset.
Raises
------
InvalidArgument
The asset had an invalid size.
Returns
-------
:class:`Asset`
The new updated asset.
"""
if not utils.valid_icon_size(size):
raise InvalidArgument("size must be a power of 2 between 16 and 4096")
url = str(yarl.URL(self._url).with_query(size=size))
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
def with_format(self, format: ValidAssetFormatTypes, /) -> Asset:
"""Returns a new asset with the specified format.
Parameters
----------
format: :class:`str`
The new format of the asset.
Raises
------
InvalidArgument
The asset had an invalid format.
Returns
-------
:class:`Asset`
The new updated asset.
"""
if self._animated:
if format not in VALID_ASSET_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_ASSET_FORMATS}")
elif format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_STATIC_FORMATS}")
url = yarl.URL(self._url)
path, _ = os.path.splitext(url.path)
url = str(url.with_path(f"{path}.{format}").with_query(url.raw_query_string))
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
def with_static_format(self, format: ValidStaticFormatTypes, /) -> Asset:
"""Returns a new asset with the specified static format.
This only changes the format if the underlying asset is
not animated. Otherwise, the asset is not changed.
Parameters
----------
format: :class:`str`
The new static format of the asset.
Raises
------
InvalidArgument
The asset had an invalid format.
Returns
-------
:class:`Asset`
The new updated asset.
"""
if self._animated:
return self
return self.with_format(format)
def _transform_icon(entry: AuditLogEntry, data: Optional[str]) -> Optional[Asset]:
if data is None:
return None
return Asset._from_guild_icon(entry._state, entry.guild.id, data) | null |
161,005 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
r"""Represents an Audit Log entry.
You retrieve these via :meth:`Guild.audit_logs`.
.. container:: operations
.. describe:: x == y
Checks if two entries are equal.
.. describe:: x != y
Checks if two entries are not equal.
.. describe:: hash(x)
Returns the entry's hash.
.. versionchanged:: 1.7
Audit log entries are now comparable and hashable.
Attributes
----------
action: :class:`AuditLogAction`
The action that was done.
user: :class:`abc.User`
The user who initiated this action. Usually a :class:`Member`\, unless gone
then it's a :class:`User`.
id: :class:`int`
The entry ID.
target: Any
The target that got changed. The exact type of this depends on
the action being done.
reason: Optional[:class:`str`]
The reason this action was done.
extra: Any
Extra information that this entry has that might be useful.
For most actions, this is ``None``. However in some cases it
contains extra information. See :class:`AuditLogAction` for
which actions have this field filled out.
"""
extra: Union[
_AuditLogProxyMemberPrune,
_AuditLogProxyMemberMoveOrMessageDelete,
_AuditLogProxyMemberDisconnect,
_AuditLogProxyPinAction,
_AuditLogProxyStageInstanceAction,
_AuditLogProxyAutoModerationBlockMessage,
Member,
User,
None,
Role,
]
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
self._state = guild._state
self.guild = guild
self._auto_moderation_rules = auto_moderation_rules
self._users = users
self._from_data(data)
def _from_data(self, data: AuditLogEntryPayload) -> None:
self.action = enums.try_enum(enums.AuditLogAction, data["action_type"])
self.id = int(data["id"])
# this key is technically not usually present
self.reason = data.get("reason")
self.extra = data.get("options", {}) # type: ignore
# I gave up trying to fix this
elems: Dict[str, Any] = {}
channel_id = int(self.extra["channel_id"]) if self.extra.get("channel_id", None) else None
if isinstance(self.action, enums.AuditLogAction) and self.extra:
if self.action is enums.AuditLogAction.member_prune:
# member prune has two keys with useful information
self.extra = type( # type: ignore
"_AuditLogProxy", (), {k: int(v) for k, v in self.extra.items()} # type: ignore
)()
elif (
self.action is enums.AuditLogAction.member_move
or self.action is enums.AuditLogAction.message_delete
):
elems = {
"count": int(self.extra["count"]),
}
elif self.action is enums.AuditLogAction.member_disconnect:
# The member disconnect action has a dict with some information
elems = {
"count": int(self.extra["count"]),
}
elif self.action.name.endswith("pin"):
# the pin actions have a dict with some information
elems = {
"message_id": int(self.extra["message_id"]),
}
elif self.action.name.startswith("overwrite_"):
# the overwrite_ actions have a dict with some information
instance_id = int(self.extra["id"])
the_type = self.extra.get("type")
if the_type == "1":
self.extra = self._get_member(instance_id)
elif the_type == "0":
role = self.guild.get_role(instance_id)
if role is None:
role = Object(id=instance_id)
role.name = self.extra.get("role_name") # type: ignore
self.extra = role # type: ignore
elif self.action.name.startswith("stage_instance"):
channel_id = int(self.extra["channel_id"])
elems = {"channel": self.guild.get_channel(channel_id) or Object(id=channel_id)}
elif (
self.action is enums.AuditLogAction.auto_moderation_block_message
or self.action is enums.AuditLogAction.auto_moderation_flag_to_channel
or self.action is enums.AuditLogAction.auto_moderation_user_communication_disabled
):
elems = {
"rule_name": self.extra["auto_moderation_rule_name"],
"rule_trigger_type": enums.try_enum(
enums.AutoModerationTriggerType,
int(self.extra["auto_moderation_rule_trigger_type"]),
),
}
# this just gets automatically filled in if present, this way prevents crashes if channel_id is None
if channel_id and self.action:
elems["channel"] = self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id)
if type(self.extra) is dict:
self.extra = type("_AuditLogProxy", (), elems)() # type: ignore
# this key is not present when the above is present, typically.
# It's a list of { new_value: a, old_value: b, key: c }
# where new_value and old_value are not guaranteed to be there depending
# on the action type, so let's just fetch it for now and only turn it
# into meaningful data when requested
self._changes = data.get("changes", [])
self.user = self._get_member(utils.get_as_snowflake(data, "user_id")) # type: ignore
self._target_id = utils.get_as_snowflake(data, "target_id")
def _get_member(self, user_id: int) -> Union[Member, User, None]:
return self.guild.get_member(user_id) or self._users.get(user_id)
def __repr__(self) -> str:
return f"<AuditLogEntry id={self.id} action={self.action} user={self.user!r}>"
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the entry's creation time in UTC."""
return utils.snowflake_time(self.id)
def target(self) -> AuditTarget:
try:
converter = getattr(self, "_convert_target_" + str(self.action.target_type))
except AttributeError:
if self._target_id is None:
return None
return Object(id=self._target_id)
else:
return converter(self._target_id)
def category(self) -> Optional[enums.AuditLogActionCategory]:
"""Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable."""
return self.action.category
def changes(self) -> AuditLogChanges:
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj
def before(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's prior state."""
return self.changes.before
def after(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's subsequent state."""
return self.changes.after
def _convert_target_guild(self, target_id: int) -> Guild:
return self.guild
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
return self.guild.get_channel(target_id) or Object(id=target_id)
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
return self.guild.get_role(target_id) or Object(id=target_id)
def _convert_target_invite(self, target_id: int) -> Invite:
# invites have target_id set to null
# so figure out which change has the full invite data
changeset = self.before if self.action is enums.AuditLogAction.invite_delete else self.after
fake_payload = {
"max_age": changeset.max_age,
"max_uses": changeset.max_uses,
"code": changeset.code,
"temporary": changeset.temporary,
"uses": changeset.uses,
}
obj = Invite(state=self._state, data=fake_payload, guild=self.guild, channel=changeset.channel) # type: ignore
with contextlib.suppress(AttributeError):
obj.inviter = changeset.inviter
return obj
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
return self._state.get_emoji(target_id) or Object(id=target_id)
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
return self.guild.get_stage_instance(target_id) or Object(id=target_id)
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
return self._state.get_sticker(target_id) or Object(id=target_id)
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
return self.guild.get_thread(target_id) or Object(id=target_id)
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
return self._auto_moderation_rules.get(rule_id) or Object(id=rule_id)
class Asset(AssetMixin):
"""Represents a CDN asset on Discord.
.. container:: operations
.. describe:: str(x)
Returns the URL of the CDN asset.
.. describe:: len(x)
Returns the length of the CDN asset's URL.
.. describe:: x == y
Checks if the asset is equal to another asset.
.. describe:: x != y
Checks if the asset is not equal to another asset.
.. describe:: hash(x)
Returns the hash of the asset.
"""
__slots__: Tuple[str, ...] = (
"_state",
"_url",
"_animated",
"_key",
)
BASE = "https://cdn.discordapp.com"
def __init__(self, state, *, url: str, key: str, animated: bool = False) -> None:
self._state = state
self._url = url
self._animated = animated
self._key = key
def _from_default_avatar(cls, state, index: int) -> Asset:
return cls(
state,
url=f"{cls.BASE}/embed/avatars/{index}.png",
key=str(index),
animated=False,
)
def _from_avatar(cls, state, user_id: int, avatar: str) -> Asset:
animated = avatar.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/avatars/{user_id}/{avatar}.{format}?size=1024",
key=avatar,
animated=animated,
)
def _from_guild_avatar(cls, state, guild_id: int, member_id: int, avatar: str) -> Asset:
animated = avatar.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/guilds/{guild_id}/users/{member_id}/avatars/{avatar}.{format}?size=1024",
key=avatar,
animated=animated,
)
def _from_icon(cls, state, object_id: int, icon_hash: str, path: str) -> Asset:
return cls(
state,
url=f"{cls.BASE}/{path}-icons/{object_id}/{icon_hash}.png?size=1024",
key=icon_hash,
animated=False,
)
def _from_cover_image(cls, state, object_id: int, cover_image_hash: str) -> Asset:
return cls(
state,
url=f"{cls.BASE}/app-assets/{object_id}/store/{cover_image_hash}.png?size=1024",
key=cover_image_hash,
animated=False,
)
def _from_guild_image(cls, state, guild_id: int, image: str, path: str) -> Asset:
animated = False
format = "png"
if path == "banners":
animated = image.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/{path}/{guild_id}/{image}.{format}?size=1024",
key=image,
animated=animated,
)
def _from_guild_icon(cls, state, guild_id: int, icon_hash: str) -> Asset:
animated = icon_hash.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/icons/{guild_id}/{icon_hash}.{format}?size=1024",
key=icon_hash,
animated=animated,
)
def _from_sticker_banner(cls, state, banner: int) -> Asset:
return cls(
state,
url=f"{cls.BASE}/app-assets/710982414301790216/store/{banner}.png",
key=str(banner),
animated=False,
)
def _from_user_banner(cls, state, user_id: int, banner_hash: str) -> Asset:
animated = banner_hash.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/banners/{user_id}/{banner_hash}.{format}?size=512",
key=banner_hash,
animated=animated,
)
def _from_scheduled_event_image(cls, state, event_id: int, image_hash: str) -> Asset:
return cls(
state,
url=f"{cls.BASE}/guild-events/{event_id}/{image_hash}.png",
key=image_hash,
animated=False,
)
def __str__(self) -> str:
return self._url
def __len__(self) -> int:
return len(self._url)
def __repr__(self) -> str:
shorten = self._url.replace(self.BASE, "")
return f"<Asset url={shorten!r}>"
def __eq__(self, other):
return isinstance(other, Asset) and self._url == other._url
def __hash__(self):
return hash(self._url)
def url(self) -> str:
""":class:`str`: Returns the underlying URL of the asset."""
return self._url
def key(self) -> str:
""":class:`str`: Returns the identifying key of the asset."""
return self._key
def is_animated(self) -> bool:
""":class:`bool`: Returns whether the asset is animated."""
return self._animated
def replace(
self,
*,
size: int = MISSING,
format: ValidAssetFormatTypes = MISSING,
static_format: ValidStaticFormatTypes = MISSING,
) -> Asset:
"""Returns a new asset with the passed components replaced.
Parameters
----------
size: :class:`int`
The new size of the asset.
format: :class:`str`
The new format to change it to. Must be either
'webp', 'jpeg', 'jpg', 'png', or 'gif' if it's animated.
static_format: :class:`str`
The new format to change it to if the asset isn't animated.
Must be either 'webp', 'jpeg', 'jpg', or 'png'.
Raises
------
InvalidArgument
An invalid size or format was passed.
Returns
-------
:class:`Asset`
The newly updated asset.
"""
url = yarl.URL(self._url)
path, _ = os.path.splitext(url.path)
if format is not MISSING:
if self._animated:
if format not in VALID_ASSET_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_ASSET_FORMATS}")
url = url.with_path(f"{path}.{format}")
elif static_format is MISSING:
if format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_STATIC_FORMATS}")
url = url.with_path(f"{path}.{format}")
if static_format is not MISSING and not self._animated:
if static_format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f"static_format must be one of {VALID_STATIC_FORMATS}")
url = url.with_path(f"{path}.{static_format}")
if size is not MISSING:
if not utils.valid_icon_size(size):
raise InvalidArgument("size must be a power of 2 between 16 and 4096")
url = url.with_query(size=size)
else:
url = url.with_query(url.raw_query_string)
url = str(url)
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
def with_size(self, size: int, /) -> Asset:
"""Returns a new asset with the specified size.
Parameters
----------
size: :class:`int`
The new size of the asset.
Raises
------
InvalidArgument
The asset had an invalid size.
Returns
-------
:class:`Asset`
The new updated asset.
"""
if not utils.valid_icon_size(size):
raise InvalidArgument("size must be a power of 2 between 16 and 4096")
url = str(yarl.URL(self._url).with_query(size=size))
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
def with_format(self, format: ValidAssetFormatTypes, /) -> Asset:
"""Returns a new asset with the specified format.
Parameters
----------
format: :class:`str`
The new format of the asset.
Raises
------
InvalidArgument
The asset had an invalid format.
Returns
-------
:class:`Asset`
The new updated asset.
"""
if self._animated:
if format not in VALID_ASSET_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_ASSET_FORMATS}")
elif format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_STATIC_FORMATS}")
url = yarl.URL(self._url)
path, _ = os.path.splitext(url.path)
url = str(url.with_path(f"{path}.{format}").with_query(url.raw_query_string))
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
def with_static_format(self, format: ValidStaticFormatTypes, /) -> Asset:
"""Returns a new asset with the specified static format.
This only changes the format if the underlying asset is
not animated. Otherwise, the asset is not changed.
Parameters
----------
format: :class:`str`
The new static format of the asset.
Raises
------
InvalidArgument
The asset had an invalid format.
Returns
-------
:class:`Asset`
The new updated asset.
"""
if self._animated:
return self
return self.with_format(format)
def _transform_avatar(entry: AuditLogEntry, data: Optional[str]) -> Optional[Asset]:
if data is None:
return None
return Asset._from_avatar(entry._state, entry._target_id, data) # type: ignore | null |
161,006 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
r"""Represents an Audit Log entry.
You retrieve these via :meth:`Guild.audit_logs`.
.. container:: operations
.. describe:: x == y
Checks if two entries are equal.
.. describe:: x != y
Checks if two entries are not equal.
.. describe:: hash(x)
Returns the entry's hash.
.. versionchanged:: 1.7
Audit log entries are now comparable and hashable.
Attributes
----------
action: :class:`AuditLogAction`
The action that was done.
user: :class:`abc.User`
The user who initiated this action. Usually a :class:`Member`\, unless gone
then it's a :class:`User`.
id: :class:`int`
The entry ID.
target: Any
The target that got changed. The exact type of this depends on
the action being done.
reason: Optional[:class:`str`]
The reason this action was done.
extra: Any
Extra information that this entry has that might be useful.
For most actions, this is ``None``. However in some cases it
contains extra information. See :class:`AuditLogAction` for
which actions have this field filled out.
"""
extra: Union[
_AuditLogProxyMemberPrune,
_AuditLogProxyMemberMoveOrMessageDelete,
_AuditLogProxyMemberDisconnect,
_AuditLogProxyPinAction,
_AuditLogProxyStageInstanceAction,
_AuditLogProxyAutoModerationBlockMessage,
Member,
User,
None,
Role,
]
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
self._state = guild._state
self.guild = guild
self._auto_moderation_rules = auto_moderation_rules
self._users = users
self._from_data(data)
def _from_data(self, data: AuditLogEntryPayload) -> None:
self.action = enums.try_enum(enums.AuditLogAction, data["action_type"])
self.id = int(data["id"])
# this key is technically not usually present
self.reason = data.get("reason")
self.extra = data.get("options", {}) # type: ignore
# I gave up trying to fix this
elems: Dict[str, Any] = {}
channel_id = int(self.extra["channel_id"]) if self.extra.get("channel_id", None) else None
if isinstance(self.action, enums.AuditLogAction) and self.extra:
if self.action is enums.AuditLogAction.member_prune:
# member prune has two keys with useful information
self.extra = type( # type: ignore
"_AuditLogProxy", (), {k: int(v) for k, v in self.extra.items()} # type: ignore
)()
elif (
self.action is enums.AuditLogAction.member_move
or self.action is enums.AuditLogAction.message_delete
):
elems = {
"count": int(self.extra["count"]),
}
elif self.action is enums.AuditLogAction.member_disconnect:
# The member disconnect action has a dict with some information
elems = {
"count": int(self.extra["count"]),
}
elif self.action.name.endswith("pin"):
# the pin actions have a dict with some information
elems = {
"message_id": int(self.extra["message_id"]),
}
elif self.action.name.startswith("overwrite_"):
# the overwrite_ actions have a dict with some information
instance_id = int(self.extra["id"])
the_type = self.extra.get("type")
if the_type == "1":
self.extra = self._get_member(instance_id)
elif the_type == "0":
role = self.guild.get_role(instance_id)
if role is None:
role = Object(id=instance_id)
role.name = self.extra.get("role_name") # type: ignore
self.extra = role # type: ignore
elif self.action.name.startswith("stage_instance"):
channel_id = int(self.extra["channel_id"])
elems = {"channel": self.guild.get_channel(channel_id) or Object(id=channel_id)}
elif (
self.action is enums.AuditLogAction.auto_moderation_block_message
or self.action is enums.AuditLogAction.auto_moderation_flag_to_channel
or self.action is enums.AuditLogAction.auto_moderation_user_communication_disabled
):
elems = {
"rule_name": self.extra["auto_moderation_rule_name"],
"rule_trigger_type": enums.try_enum(
enums.AutoModerationTriggerType,
int(self.extra["auto_moderation_rule_trigger_type"]),
),
}
# this just gets automatically filled in if present, this way prevents crashes if channel_id is None
if channel_id and self.action:
elems["channel"] = self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id)
if type(self.extra) is dict:
self.extra = type("_AuditLogProxy", (), elems)() # type: ignore
# this key is not present when the above is present, typically.
# It's a list of { new_value: a, old_value: b, key: c }
# where new_value and old_value are not guaranteed to be there depending
# on the action type, so let's just fetch it for now and only turn it
# into meaningful data when requested
self._changes = data.get("changes", [])
self.user = self._get_member(utils.get_as_snowflake(data, "user_id")) # type: ignore
self._target_id = utils.get_as_snowflake(data, "target_id")
def _get_member(self, user_id: int) -> Union[Member, User, None]:
return self.guild.get_member(user_id) or self._users.get(user_id)
def __repr__(self) -> str:
return f"<AuditLogEntry id={self.id} action={self.action} user={self.user!r}>"
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the entry's creation time in UTC."""
return utils.snowflake_time(self.id)
def target(self) -> AuditTarget:
try:
converter = getattr(self, "_convert_target_" + str(self.action.target_type))
except AttributeError:
if self._target_id is None:
return None
return Object(id=self._target_id)
else:
return converter(self._target_id)
def category(self) -> Optional[enums.AuditLogActionCategory]:
"""Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable."""
return self.action.category
def changes(self) -> AuditLogChanges:
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj
def before(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's prior state."""
return self.changes.before
def after(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's subsequent state."""
return self.changes.after
def _convert_target_guild(self, target_id: int) -> Guild:
return self.guild
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
return self.guild.get_channel(target_id) or Object(id=target_id)
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
return self.guild.get_role(target_id) or Object(id=target_id)
def _convert_target_invite(self, target_id: int) -> Invite:
# invites have target_id set to null
# so figure out which change has the full invite data
changeset = self.before if self.action is enums.AuditLogAction.invite_delete else self.after
fake_payload = {
"max_age": changeset.max_age,
"max_uses": changeset.max_uses,
"code": changeset.code,
"temporary": changeset.temporary,
"uses": changeset.uses,
}
obj = Invite(state=self._state, data=fake_payload, guild=self.guild, channel=changeset.channel) # type: ignore
with contextlib.suppress(AttributeError):
obj.inviter = changeset.inviter
return obj
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
return self._state.get_emoji(target_id) or Object(id=target_id)
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
return self.guild.get_stage_instance(target_id) or Object(id=target_id)
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
return self._state.get_sticker(target_id) or Object(id=target_id)
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
return self.guild.get_thread(target_id) or Object(id=target_id)
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
return self._auto_moderation_rules.get(rule_id) or Object(id=rule_id)
class Asset(AssetMixin):
"""Represents a CDN asset on Discord.
.. container:: operations
.. describe:: str(x)
Returns the URL of the CDN asset.
.. describe:: len(x)
Returns the length of the CDN asset's URL.
.. describe:: x == y
Checks if the asset is equal to another asset.
.. describe:: x != y
Checks if the asset is not equal to another asset.
.. describe:: hash(x)
Returns the hash of the asset.
"""
__slots__: Tuple[str, ...] = (
"_state",
"_url",
"_animated",
"_key",
)
BASE = "https://cdn.discordapp.com"
def __init__(self, state, *, url: str, key: str, animated: bool = False) -> None:
self._state = state
self._url = url
self._animated = animated
self._key = key
def _from_default_avatar(cls, state, index: int) -> Asset:
return cls(
state,
url=f"{cls.BASE}/embed/avatars/{index}.png",
key=str(index),
animated=False,
)
def _from_avatar(cls, state, user_id: int, avatar: str) -> Asset:
animated = avatar.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/avatars/{user_id}/{avatar}.{format}?size=1024",
key=avatar,
animated=animated,
)
def _from_guild_avatar(cls, state, guild_id: int, member_id: int, avatar: str) -> Asset:
animated = avatar.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/guilds/{guild_id}/users/{member_id}/avatars/{avatar}.{format}?size=1024",
key=avatar,
animated=animated,
)
def _from_icon(cls, state, object_id: int, icon_hash: str, path: str) -> Asset:
return cls(
state,
url=f"{cls.BASE}/{path}-icons/{object_id}/{icon_hash}.png?size=1024",
key=icon_hash,
animated=False,
)
def _from_cover_image(cls, state, object_id: int, cover_image_hash: str) -> Asset:
return cls(
state,
url=f"{cls.BASE}/app-assets/{object_id}/store/{cover_image_hash}.png?size=1024",
key=cover_image_hash,
animated=False,
)
def _from_guild_image(cls, state, guild_id: int, image: str, path: str) -> Asset:
animated = False
format = "png"
if path == "banners":
animated = image.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/{path}/{guild_id}/{image}.{format}?size=1024",
key=image,
animated=animated,
)
def _from_guild_icon(cls, state, guild_id: int, icon_hash: str) -> Asset:
animated = icon_hash.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/icons/{guild_id}/{icon_hash}.{format}?size=1024",
key=icon_hash,
animated=animated,
)
def _from_sticker_banner(cls, state, banner: int) -> Asset:
return cls(
state,
url=f"{cls.BASE}/app-assets/710982414301790216/store/{banner}.png",
key=str(banner),
animated=False,
)
def _from_user_banner(cls, state, user_id: int, banner_hash: str) -> Asset:
animated = banner_hash.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/banners/{user_id}/{banner_hash}.{format}?size=512",
key=banner_hash,
animated=animated,
)
def _from_scheduled_event_image(cls, state, event_id: int, image_hash: str) -> Asset:
return cls(
state,
url=f"{cls.BASE}/guild-events/{event_id}/{image_hash}.png",
key=image_hash,
animated=False,
)
def __str__(self) -> str:
return self._url
def __len__(self) -> int:
return len(self._url)
def __repr__(self) -> str:
shorten = self._url.replace(self.BASE, "")
return f"<Asset url={shorten!r}>"
def __eq__(self, other):
return isinstance(other, Asset) and self._url == other._url
def __hash__(self):
return hash(self._url)
def url(self) -> str:
""":class:`str`: Returns the underlying URL of the asset."""
return self._url
def key(self) -> str:
""":class:`str`: Returns the identifying key of the asset."""
return self._key
def is_animated(self) -> bool:
""":class:`bool`: Returns whether the asset is animated."""
return self._animated
def replace(
self,
*,
size: int = MISSING,
format: ValidAssetFormatTypes = MISSING,
static_format: ValidStaticFormatTypes = MISSING,
) -> Asset:
"""Returns a new asset with the passed components replaced.
Parameters
----------
size: :class:`int`
The new size of the asset.
format: :class:`str`
The new format to change it to. Must be either
'webp', 'jpeg', 'jpg', 'png', or 'gif' if it's animated.
static_format: :class:`str`
The new format to change it to if the asset isn't animated.
Must be either 'webp', 'jpeg', 'jpg', or 'png'.
Raises
------
InvalidArgument
An invalid size or format was passed.
Returns
-------
:class:`Asset`
The newly updated asset.
"""
url = yarl.URL(self._url)
path, _ = os.path.splitext(url.path)
if format is not MISSING:
if self._animated:
if format not in VALID_ASSET_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_ASSET_FORMATS}")
url = url.with_path(f"{path}.{format}")
elif static_format is MISSING:
if format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_STATIC_FORMATS}")
url = url.with_path(f"{path}.{format}")
if static_format is not MISSING and not self._animated:
if static_format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f"static_format must be one of {VALID_STATIC_FORMATS}")
url = url.with_path(f"{path}.{static_format}")
if size is not MISSING:
if not utils.valid_icon_size(size):
raise InvalidArgument("size must be a power of 2 between 16 and 4096")
url = url.with_query(size=size)
else:
url = url.with_query(url.raw_query_string)
url = str(url)
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
def with_size(self, size: int, /) -> Asset:
"""Returns a new asset with the specified size.
Parameters
----------
size: :class:`int`
The new size of the asset.
Raises
------
InvalidArgument
The asset had an invalid size.
Returns
-------
:class:`Asset`
The new updated asset.
"""
if not utils.valid_icon_size(size):
raise InvalidArgument("size must be a power of 2 between 16 and 4096")
url = str(yarl.URL(self._url).with_query(size=size))
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
def with_format(self, format: ValidAssetFormatTypes, /) -> Asset:
"""Returns a new asset with the specified format.
Parameters
----------
format: :class:`str`
The new format of the asset.
Raises
------
InvalidArgument
The asset had an invalid format.
Returns
-------
:class:`Asset`
The new updated asset.
"""
if self._animated:
if format not in VALID_ASSET_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_ASSET_FORMATS}")
elif format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_STATIC_FORMATS}")
url = yarl.URL(self._url)
path, _ = os.path.splitext(url.path)
url = str(url.with_path(f"{path}.{format}").with_query(url.raw_query_string))
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
def with_static_format(self, format: ValidStaticFormatTypes, /) -> Asset:
"""Returns a new asset with the specified static format.
This only changes the format if the underlying asset is
not animated. Otherwise, the asset is not changed.
Parameters
----------
format: :class:`str`
The new static format of the asset.
Raises
------
InvalidArgument
The asset had an invalid format.
Returns
-------
:class:`Asset`
The new updated asset.
"""
if self._animated:
return self
return self.with_format(format)
def _guild_hash_transformer(path: str) -> Callable[[AuditLogEntry, Optional[str]], Optional[Asset]]:
def _transform(entry: AuditLogEntry, data: Optional[str]) -> Optional[Asset]:
if data is None:
return None
return Asset._from_guild_image(entry._state, entry.guild.id, data, path=path)
return _transform | null |
161,007 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
E = TypeVar("E", bound=enums.Enum)
class AuditLogEntry(Hashable):
r"""Represents an Audit Log entry.
You retrieve these via :meth:`Guild.audit_logs`.
.. container:: operations
.. describe:: x == y
Checks if two entries are equal.
.. describe:: x != y
Checks if two entries are not equal.
.. describe:: hash(x)
Returns the entry's hash.
.. versionchanged:: 1.7
Audit log entries are now comparable and hashable.
Attributes
----------
action: :class:`AuditLogAction`
The action that was done.
user: :class:`abc.User`
The user who initiated this action. Usually a :class:`Member`\, unless gone
then it's a :class:`User`.
id: :class:`int`
The entry ID.
target: Any
The target that got changed. The exact type of this depends on
the action being done.
reason: Optional[:class:`str`]
The reason this action was done.
extra: Any
Extra information that this entry has that might be useful.
For most actions, this is ``None``. However in some cases it
contains extra information. See :class:`AuditLogAction` for
which actions have this field filled out.
"""
extra: Union[
_AuditLogProxyMemberPrune,
_AuditLogProxyMemberMoveOrMessageDelete,
_AuditLogProxyMemberDisconnect,
_AuditLogProxyPinAction,
_AuditLogProxyStageInstanceAction,
_AuditLogProxyAutoModerationBlockMessage,
Member,
User,
None,
Role,
]
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
self._state = guild._state
self.guild = guild
self._auto_moderation_rules = auto_moderation_rules
self._users = users
self._from_data(data)
def _from_data(self, data: AuditLogEntryPayload) -> None:
self.action = enums.try_enum(enums.AuditLogAction, data["action_type"])
self.id = int(data["id"])
# this key is technically not usually present
self.reason = data.get("reason")
self.extra = data.get("options", {}) # type: ignore
# I gave up trying to fix this
elems: Dict[str, Any] = {}
channel_id = int(self.extra["channel_id"]) if self.extra.get("channel_id", None) else None
if isinstance(self.action, enums.AuditLogAction) and self.extra:
if self.action is enums.AuditLogAction.member_prune:
# member prune has two keys with useful information
self.extra = type( # type: ignore
"_AuditLogProxy", (), {k: int(v) for k, v in self.extra.items()} # type: ignore
)()
elif (
self.action is enums.AuditLogAction.member_move
or self.action is enums.AuditLogAction.message_delete
):
elems = {
"count": int(self.extra["count"]),
}
elif self.action is enums.AuditLogAction.member_disconnect:
# The member disconnect action has a dict with some information
elems = {
"count": int(self.extra["count"]),
}
elif self.action.name.endswith("pin"):
# the pin actions have a dict with some information
elems = {
"message_id": int(self.extra["message_id"]),
}
elif self.action.name.startswith("overwrite_"):
# the overwrite_ actions have a dict with some information
instance_id = int(self.extra["id"])
the_type = self.extra.get("type")
if the_type == "1":
self.extra = self._get_member(instance_id)
elif the_type == "0":
role = self.guild.get_role(instance_id)
if role is None:
role = Object(id=instance_id)
role.name = self.extra.get("role_name") # type: ignore
self.extra = role # type: ignore
elif self.action.name.startswith("stage_instance"):
channel_id = int(self.extra["channel_id"])
elems = {"channel": self.guild.get_channel(channel_id) or Object(id=channel_id)}
elif (
self.action is enums.AuditLogAction.auto_moderation_block_message
or self.action is enums.AuditLogAction.auto_moderation_flag_to_channel
or self.action is enums.AuditLogAction.auto_moderation_user_communication_disabled
):
elems = {
"rule_name": self.extra["auto_moderation_rule_name"],
"rule_trigger_type": enums.try_enum(
enums.AutoModerationTriggerType,
int(self.extra["auto_moderation_rule_trigger_type"]),
),
}
# this just gets automatically filled in if present, this way prevents crashes if channel_id is None
if channel_id and self.action:
elems["channel"] = self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id)
if type(self.extra) is dict:
self.extra = type("_AuditLogProxy", (), elems)() # type: ignore
# this key is not present when the above is present, typically.
# It's a list of { new_value: a, old_value: b, key: c }
# where new_value and old_value are not guaranteed to be there depending
# on the action type, so let's just fetch it for now and only turn it
# into meaningful data when requested
self._changes = data.get("changes", [])
self.user = self._get_member(utils.get_as_snowflake(data, "user_id")) # type: ignore
self._target_id = utils.get_as_snowflake(data, "target_id")
def _get_member(self, user_id: int) -> Union[Member, User, None]:
return self.guild.get_member(user_id) or self._users.get(user_id)
def __repr__(self) -> str:
return f"<AuditLogEntry id={self.id} action={self.action} user={self.user!r}>"
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the entry's creation time in UTC."""
return utils.snowflake_time(self.id)
def target(self) -> AuditTarget:
try:
converter = getattr(self, "_convert_target_" + str(self.action.target_type))
except AttributeError:
if self._target_id is None:
return None
return Object(id=self._target_id)
else:
return converter(self._target_id)
def category(self) -> Optional[enums.AuditLogActionCategory]:
"""Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable."""
return self.action.category
def changes(self) -> AuditLogChanges:
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj
def before(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's prior state."""
return self.changes.before
def after(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's subsequent state."""
return self.changes.after
def _convert_target_guild(self, target_id: int) -> Guild:
return self.guild
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
return self.guild.get_channel(target_id) or Object(id=target_id)
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
return self.guild.get_role(target_id) or Object(id=target_id)
def _convert_target_invite(self, target_id: int) -> Invite:
# invites have target_id set to null
# so figure out which change has the full invite data
changeset = self.before if self.action is enums.AuditLogAction.invite_delete else self.after
fake_payload = {
"max_age": changeset.max_age,
"max_uses": changeset.max_uses,
"code": changeset.code,
"temporary": changeset.temporary,
"uses": changeset.uses,
}
obj = Invite(state=self._state, data=fake_payload, guild=self.guild, channel=changeset.channel) # type: ignore
with contextlib.suppress(AttributeError):
obj.inviter = changeset.inviter
return obj
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
return self._state.get_emoji(target_id) or Object(id=target_id)
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
return self.guild.get_stage_instance(target_id) or Object(id=target_id)
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
return self._state.get_sticker(target_id) or Object(id=target_id)
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
return self.guild.get_thread(target_id) or Object(id=target_id)
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
return self._auto_moderation_rules.get(rule_id) or Object(id=rule_id)
def _enum_transformer(enum: Type[E]) -> Callable[[AuditLogEntry, int], E]:
def _transform(_entry: AuditLogEntry, data: int) -> E:
return enums.try_enum(enum, data)
return _transform | null |
161,008 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
def _from_data(self, data: AuditLogEntryPayload) -> None:
def _get_member(self, user_id: int) -> Union[Member, User, None]:
def __repr__(self) -> str:
def created_at(self) -> datetime.datetime:
def target(self) -> AuditTarget:
def category(self) -> Optional[enums.AuditLogActionCategory]:
def changes(self) -> AuditLogChanges:
def before(self) -> AuditLogDiff:
def after(self) -> AuditLogDiff:
def _convert_target_guild(self, target_id: int) -> Guild:
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
def _convert_target_invite(self, target_id: int) -> Invite:
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
def _transform_type(entry: AuditLogEntry, data: int) -> Union[enums.ChannelType, enums.StickerType]:
if entry.action.name.startswith("sticker_"):
return enums.try_enum(enums.StickerType, data)
return enums.try_enum(enums.ChannelType, data) | null |
161,009 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
T = TypeVar("T")
class AuditLogEntry(Hashable):
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
def _from_data(self, data: AuditLogEntryPayload) -> None:
def _get_member(self, user_id: int) -> Union[Member, User, None]:
def __repr__(self) -> str:
def created_at(self) -> datetime.datetime:
def target(self) -> AuditTarget:
def category(self) -> Optional[enums.AuditLogActionCategory]:
def changes(self) -> AuditLogChanges:
def before(self) -> AuditLogDiff:
def after(self) -> AuditLogDiff:
def _convert_target_guild(self, target_id: int) -> Guild:
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
def _convert_target_invite(self, target_id: int) -> Invite:
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
def _list_transformer(
func: Callable[[AuditLogEntry, Any], T]
) -> Callable[[AuditLogEntry, Any], List[T]]:
def _transform(entry: AuditLogEntry, data: Any) -> List[T]:
if not data:
return []
return [func(entry, value) for value in data if value is not None]
return _transform | null |
161,010 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
r"""Represents an Audit Log entry.
You retrieve these via :meth:`Guild.audit_logs`.
.. container:: operations
.. describe:: x == y
Checks if two entries are equal.
.. describe:: x != y
Checks if two entries are not equal.
.. describe:: hash(x)
Returns the entry's hash.
.. versionchanged:: 1.7
Audit log entries are now comparable and hashable.
Attributes
----------
action: :class:`AuditLogAction`
The action that was done.
user: :class:`abc.User`
The user who initiated this action. Usually a :class:`Member`\, unless gone
then it's a :class:`User`.
id: :class:`int`
The entry ID.
target: Any
The target that got changed. The exact type of this depends on
the action being done.
reason: Optional[:class:`str`]
The reason this action was done.
extra: Any
Extra information that this entry has that might be useful.
For most actions, this is ``None``. However in some cases it
contains extra information. See :class:`AuditLogAction` for
which actions have this field filled out.
"""
extra: Union[
_AuditLogProxyMemberPrune,
_AuditLogProxyMemberMoveOrMessageDelete,
_AuditLogProxyMemberDisconnect,
_AuditLogProxyPinAction,
_AuditLogProxyStageInstanceAction,
_AuditLogProxyAutoModerationBlockMessage,
Member,
User,
None,
Role,
]
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
self._state = guild._state
self.guild = guild
self._auto_moderation_rules = auto_moderation_rules
self._users = users
self._from_data(data)
def _from_data(self, data: AuditLogEntryPayload) -> None:
self.action = enums.try_enum(enums.AuditLogAction, data["action_type"])
self.id = int(data["id"])
# this key is technically not usually present
self.reason = data.get("reason")
self.extra = data.get("options", {}) # type: ignore
# I gave up trying to fix this
elems: Dict[str, Any] = {}
channel_id = int(self.extra["channel_id"]) if self.extra.get("channel_id", None) else None
if isinstance(self.action, enums.AuditLogAction) and self.extra:
if self.action is enums.AuditLogAction.member_prune:
# member prune has two keys with useful information
self.extra = type( # type: ignore
"_AuditLogProxy", (), {k: int(v) for k, v in self.extra.items()} # type: ignore
)()
elif (
self.action is enums.AuditLogAction.member_move
or self.action is enums.AuditLogAction.message_delete
):
elems = {
"count": int(self.extra["count"]),
}
elif self.action is enums.AuditLogAction.member_disconnect:
# The member disconnect action has a dict with some information
elems = {
"count": int(self.extra["count"]),
}
elif self.action.name.endswith("pin"):
# the pin actions have a dict with some information
elems = {
"message_id": int(self.extra["message_id"]),
}
elif self.action.name.startswith("overwrite_"):
# the overwrite_ actions have a dict with some information
instance_id = int(self.extra["id"])
the_type = self.extra.get("type")
if the_type == "1":
self.extra = self._get_member(instance_id)
elif the_type == "0":
role = self.guild.get_role(instance_id)
if role is None:
role = Object(id=instance_id)
role.name = self.extra.get("role_name") # type: ignore
self.extra = role # type: ignore
elif self.action.name.startswith("stage_instance"):
channel_id = int(self.extra["channel_id"])
elems = {"channel": self.guild.get_channel(channel_id) or Object(id=channel_id)}
elif (
self.action is enums.AuditLogAction.auto_moderation_block_message
or self.action is enums.AuditLogAction.auto_moderation_flag_to_channel
or self.action is enums.AuditLogAction.auto_moderation_user_communication_disabled
):
elems = {
"rule_name": self.extra["auto_moderation_rule_name"],
"rule_trigger_type": enums.try_enum(
enums.AutoModerationTriggerType,
int(self.extra["auto_moderation_rule_trigger_type"]),
),
}
# this just gets automatically filled in if present, this way prevents crashes if channel_id is None
if channel_id and self.action:
elems["channel"] = self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id)
if type(self.extra) is dict:
self.extra = type("_AuditLogProxy", (), elems)() # type: ignore
# this key is not present when the above is present, typically.
# It's a list of { new_value: a, old_value: b, key: c }
# where new_value and old_value are not guaranteed to be there depending
# on the action type, so let's just fetch it for now and only turn it
# into meaningful data when requested
self._changes = data.get("changes", [])
self.user = self._get_member(utils.get_as_snowflake(data, "user_id")) # type: ignore
self._target_id = utils.get_as_snowflake(data, "target_id")
def _get_member(self, user_id: int) -> Union[Member, User, None]:
return self.guild.get_member(user_id) or self._users.get(user_id)
def __repr__(self) -> str:
return f"<AuditLogEntry id={self.id} action={self.action} user={self.user!r}>"
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the entry's creation time in UTC."""
return utils.snowflake_time(self.id)
def target(self) -> AuditTarget:
try:
converter = getattr(self, "_convert_target_" + str(self.action.target_type))
except AttributeError:
if self._target_id is None:
return None
return Object(id=self._target_id)
else:
return converter(self._target_id)
def category(self) -> Optional[enums.AuditLogActionCategory]:
"""Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable."""
return self.action.category
def changes(self) -> AuditLogChanges:
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj
def before(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's prior state."""
return self.changes.before
def after(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's subsequent state."""
return self.changes.after
def _convert_target_guild(self, target_id: int) -> Guild:
return self.guild
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
return self.guild.get_channel(target_id) or Object(id=target_id)
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
return self.guild.get_role(target_id) or Object(id=target_id)
def _convert_target_invite(self, target_id: int) -> Invite:
# invites have target_id set to null
# so figure out which change has the full invite data
changeset = self.before if self.action is enums.AuditLogAction.invite_delete else self.after
fake_payload = {
"max_age": changeset.max_age,
"max_uses": changeset.max_uses,
"code": changeset.code,
"temporary": changeset.temporary,
"uses": changeset.uses,
}
obj = Invite(state=self._state, data=fake_payload, guild=self.guild, channel=changeset.channel) # type: ignore
with contextlib.suppress(AttributeError):
obj.inviter = changeset.inviter
return obj
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
return self._state.get_emoji(target_id) or Object(id=target_id)
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
return self.guild.get_stage_instance(target_id) or Object(id=target_id)
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
return self._state.get_sticker(target_id) or Object(id=target_id)
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
return self.guild.get_thread(target_id) or Object(id=target_id)
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
return self._auto_moderation_rules.get(rule_id) or Object(id=rule_id)
class AutoModerationAction:
"""Represents an auto moderation action that will execute whenever a rule is triggered.
.. versionadded:: 2.1
Parameters
----------
type: :class:`AutoModerationActionType`
The type to use for this action.
metadata: :class:`AutoModerationActionMetadata`
The additional data to use during execution of this action.
Attributes
----------
type: :class:`AutoModerationActionType`
The type of this action.
metadata: :class:`AutoModerationActionMetadata`
The additional metadata needed during execution for this specific action type.
"""
__slots__ = ("type", "metadata")
def __init__(
self,
*,
type: AutoModerationActionType,
metadata: Optional[AutoModerationActionMetadata] = None,
) -> None:
self.type: AutoModerationActionType = type
self.metadata: Optional[AutoModerationActionMetadata] = metadata
def from_data(cls, data: AutoModerationActionPayload) -> AutoModerationAction:
type = try_enum(AutoModerationActionType, data["type"])
metadata = AutoModerationActionMetadata.from_data(data.get("metadata", {}))
return cls(type=type, metadata=metadata)
def payload(self) -> AutoModerationActionPayload:
data: AutoModerationActionPayload = {
"type": self.type.value,
}
if self.metadata is not None:
data["metadata"] = self.metadata.payload
return data
class AutoModerationAction(TypedDict):
type: AutoModerationActionType
metadata: NotRequired[AutoModerationActionMetadata]
def _transform_auto_moderation_action(
_entry: AuditLogEntry, data: Optional[AutoModerationActionPayload]
) -> Optional[AutoModerationAction]:
if data is None:
return None
return AutoModerationAction.from_data(data) | null |
161,011 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
def _from_data(self, data: AuditLogEntryPayload) -> None:
def _get_member(self, user_id: int) -> Union[Member, User, None]:
def __repr__(self) -> str:
def created_at(self) -> datetime.datetime:
def target(self) -> AuditTarget:
def category(self) -> Optional[enums.AuditLogActionCategory]:
def changes(self) -> AuditLogChanges:
def before(self) -> AuditLogDiff:
def after(self) -> AuditLogDiff:
def _convert_target_guild(self, target_id: int) -> Guild:
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
def _convert_target_invite(self, target_id: int) -> Invite:
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
class AutoModerationTriggerMetadata:
def __init__(
self,
*,
keyword_filter: Optional[List[str]] = None,
regex_patterns: Optional[List[str]] = None,
presets: Optional[List[KeywordPresetType]] = None,
allow_list: Optional[List[str]] = None,
mention_total_limit: Optional[int] = None,
mention_raid_protection_enabled: Optional[bool] = None,
) -> None:
def from_data(cls, data: TriggerMetadataPayload):
def payload(self) -> TriggerMetadataPayload:
def _transform_auto_moderation_trigger_metadata(
_entry: AuditLogEntry, data: Optional[AutoModerationTriggerMetadataPayload]
) -> Optional[AutoModerationTriggerMetadata]:
if data is None:
return None
return AutoModerationTriggerMetadata.from_data(data) | null |
161,012 | from __future__ import annotations
import contextlib
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from . import enums, utils
from .asset import Asset
from .auto_moderation import AutoModerationAction, AutoModerationTriggerMetadata
from .colour import Colour
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .permissions import PermissionOverwrite, Permissions
class AuditLogEntry(Hashable):
r"""Represents an Audit Log entry.
You retrieve these via :meth:`Guild.audit_logs`.
.. container:: operations
.. describe:: x == y
Checks if two entries are equal.
.. describe:: x != y
Checks if two entries are not equal.
.. describe:: hash(x)
Returns the entry's hash.
.. versionchanged:: 1.7
Audit log entries are now comparable and hashable.
Attributes
----------
action: :class:`AuditLogAction`
The action that was done.
user: :class:`abc.User`
The user who initiated this action. Usually a :class:`Member`\, unless gone
then it's a :class:`User`.
id: :class:`int`
The entry ID.
target: Any
The target that got changed. The exact type of this depends on
the action being done.
reason: Optional[:class:`str`]
The reason this action was done.
extra: Any
Extra information that this entry has that might be useful.
For most actions, this is ``None``. However in some cases it
contains extra information. See :class:`AuditLogAction` for
which actions have this field filled out.
"""
extra: Union[
_AuditLogProxyMemberPrune,
_AuditLogProxyMemberMoveOrMessageDelete,
_AuditLogProxyMemberDisconnect,
_AuditLogProxyPinAction,
_AuditLogProxyStageInstanceAction,
_AuditLogProxyAutoModerationBlockMessage,
Member,
User,
None,
Role,
]
def __init__(
self,
*,
auto_moderation_rules: Dict[int, AutoModerationRule],
users: Dict[int, User],
data: AuditLogEntryPayload,
guild: Guild,
) -> None:
self._state = guild._state
self.guild = guild
self._auto_moderation_rules = auto_moderation_rules
self._users = users
self._from_data(data)
def _from_data(self, data: AuditLogEntryPayload) -> None:
self.action = enums.try_enum(enums.AuditLogAction, data["action_type"])
self.id = int(data["id"])
# this key is technically not usually present
self.reason = data.get("reason")
self.extra = data.get("options", {}) # type: ignore
# I gave up trying to fix this
elems: Dict[str, Any] = {}
channel_id = int(self.extra["channel_id"]) if self.extra.get("channel_id", None) else None
if isinstance(self.action, enums.AuditLogAction) and self.extra:
if self.action is enums.AuditLogAction.member_prune:
# member prune has two keys with useful information
self.extra = type( # type: ignore
"_AuditLogProxy", (), {k: int(v) for k, v in self.extra.items()} # type: ignore
)()
elif (
self.action is enums.AuditLogAction.member_move
or self.action is enums.AuditLogAction.message_delete
):
elems = {
"count": int(self.extra["count"]),
}
elif self.action is enums.AuditLogAction.member_disconnect:
# The member disconnect action has a dict with some information
elems = {
"count": int(self.extra["count"]),
}
elif self.action.name.endswith("pin"):
# the pin actions have a dict with some information
elems = {
"message_id": int(self.extra["message_id"]),
}
elif self.action.name.startswith("overwrite_"):
# the overwrite_ actions have a dict with some information
instance_id = int(self.extra["id"])
the_type = self.extra.get("type")
if the_type == "1":
self.extra = self._get_member(instance_id)
elif the_type == "0":
role = self.guild.get_role(instance_id)
if role is None:
role = Object(id=instance_id)
role.name = self.extra.get("role_name") # type: ignore
self.extra = role # type: ignore
elif self.action.name.startswith("stage_instance"):
channel_id = int(self.extra["channel_id"])
elems = {"channel": self.guild.get_channel(channel_id) or Object(id=channel_id)}
elif (
self.action is enums.AuditLogAction.auto_moderation_block_message
or self.action is enums.AuditLogAction.auto_moderation_flag_to_channel
or self.action is enums.AuditLogAction.auto_moderation_user_communication_disabled
):
elems = {
"rule_name": self.extra["auto_moderation_rule_name"],
"rule_trigger_type": enums.try_enum(
enums.AutoModerationTriggerType,
int(self.extra["auto_moderation_rule_trigger_type"]),
),
}
# this just gets automatically filled in if present, this way prevents crashes if channel_id is None
if channel_id and self.action:
elems["channel"] = self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id)
if type(self.extra) is dict:
self.extra = type("_AuditLogProxy", (), elems)() # type: ignore
# this key is not present when the above is present, typically.
# It's a list of { new_value: a, old_value: b, key: c }
# where new_value and old_value are not guaranteed to be there depending
# on the action type, so let's just fetch it for now and only turn it
# into meaningful data when requested
self._changes = data.get("changes", [])
self.user = self._get_member(utils.get_as_snowflake(data, "user_id")) # type: ignore
self._target_id = utils.get_as_snowflake(data, "target_id")
def _get_member(self, user_id: int) -> Union[Member, User, None]:
return self.guild.get_member(user_id) or self._users.get(user_id)
def __repr__(self) -> str:
return f"<AuditLogEntry id={self.id} action={self.action} user={self.user!r}>"
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the entry's creation time in UTC."""
return utils.snowflake_time(self.id)
def target(self) -> AuditTarget:
try:
converter = getattr(self, "_convert_target_" + str(self.action.target_type))
except AttributeError:
if self._target_id is None:
return None
return Object(id=self._target_id)
else:
return converter(self._target_id)
def category(self) -> Optional[enums.AuditLogActionCategory]:
"""Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable."""
return self.action.category
def changes(self) -> AuditLogChanges:
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj
def before(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's prior state."""
return self.changes.before
def after(self) -> AuditLogDiff:
""":class:`AuditLogDiff`: The target's subsequent state."""
return self.changes.after
def _convert_target_guild(self, target_id: int) -> Guild:
return self.guild
def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]:
return self.guild.get_channel(target_id) or Object(id=target_id)
def _convert_target_user(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_role(self, target_id: int) -> Union[Role, Object]:
return self.guild.get_role(target_id) or Object(id=target_id)
def _convert_target_invite(self, target_id: int) -> Invite:
# invites have target_id set to null
# so figure out which change has the full invite data
changeset = self.before if self.action is enums.AuditLogAction.invite_delete else self.after
fake_payload = {
"max_age": changeset.max_age,
"max_uses": changeset.max_uses,
"code": changeset.code,
"temporary": changeset.temporary,
"uses": changeset.uses,
}
obj = Invite(state=self._state, data=fake_payload, guild=self.guild, channel=changeset.channel) # type: ignore
with contextlib.suppress(AttributeError):
obj.inviter = changeset.inviter
return obj
def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]:
return self._state.get_emoji(target_id) or Object(id=target_id)
def _convert_target_message(self, target_id: int) -> Union[Member, User, None]:
return self._get_member(target_id)
def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]:
return self.guild.get_stage_instance(target_id) or Object(id=target_id)
def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]:
return self._state.get_sticker(target_id) or Object(id=target_id)
def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
return self.guild.get_thread(target_id) or Object(id=target_id)
def _convert_target_auto_moderation_rule(
self, rule_id: int
) -> Union[AutoModerationRule, Object]:
return self._auto_moderation_rules.get(rule_id) or Object(id=rule_id)
class Object(Hashable):
"""Represents a generic Discord object.
The purpose of this class is to allow you to create 'miniature'
versions of data classes if you want to pass in just an ID. Most functions
that take in a specific data class with an ID can also take in this class
as a substitute instead. Note that even though this is the case, not all
objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received
in :dpyissue:`strange order <21>` and when such events happened you would
receive this class rather than the actual data class. These cases are
extremely rare.
.. container:: operations
.. describe:: x == y
Checks if two objects are equal.
.. describe:: x != y
Checks if two objects are not equal.
.. describe:: hash(x)
Returns the object's hash.
Attributes
----------
id: :class:`int`
The ID of the object.
"""
def __init__(self, id: SupportsIntCast) -> None:
try:
id = int(id)
except ValueError:
raise TypeError(
f"id parameter must be convertable to int not {id.__class__!r}"
) from None
else:
self.id = id
def __repr__(self) -> str:
return f"<Object id={self.id!r}>"
def __int__(self) -> int:
return self.id
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the snowflake's creation time in UTC."""
return utils.snowflake_time(self.id)
class Role(Hashable):
"""Represents a Discord role in a :class:`Guild`.
.. container:: operations
.. describe:: x == y
Checks if two roles are equal.
.. describe:: x != y
Checks if two roles are not equal.
.. describe:: x > y
Checks if a role is higher than another in the hierarchy.
.. describe:: x < y
Checks if a role is lower than another in the hierarchy.
.. describe:: x >= y
Checks if a role is higher or equal to another in the hierarchy.
.. describe:: x <= y
Checks if a role is lower or equal to another in the hierarchy.
.. describe:: hash(x)
Return the role's hash.
.. describe:: str(x)
Returns the role's name.
Attributes
----------
id: :class:`int`
The ID for the role.
name: :class:`str`
The name of the role.
guild: :class:`Guild`
The guild the role belongs to.
hoist: :class:`bool`
Indicates if the role will be displayed separately from other members.
position: :class:`int`
The position of the role. This number is usually positive. The bottom
role has a position of 0.
.. warning::
Multiple roles can have the same position number. As a consequence
of this, comparing via role position is prone to subtle bugs if
checking for role hierarchy. The recommended and correct way to
compare for roles in the hierarchy is using the comparison
operators on the role objects themselves.
managed: :class:`bool`
Indicates if the role is managed by the guild through some form of
integrations such as Twitch.
mentionable: :class:`bool`
Indicates if the role can be mentioned by users.
tags: Optional[:class:`RoleTags`]
The role tags associated with this role.
"""
__slots__ = (
"id",
"name",
"_permissions",
"_colour",
"position",
"managed",
"mentionable",
"hoist",
"guild",
"tags",
"_icon",
"_state",
"_flags",
)
def __init__(self, *, guild: Guild, state: ConnectionState, data: RolePayload) -> None:
self.guild: Guild = guild
self._state: ConnectionState = state
self.id: int = int(data["id"])
self._update(data)
def __str__(self) -> str:
return self.name
def __repr__(self) -> str:
return f"<Role id={self.id} name={self.name!r}>"
def __lt__(self, other: Self) -> bool:
if not isinstance(other, Role) or not isinstance(self, Role):
return NotImplemented
if self.guild != other.guild:
raise RuntimeError("Cannot compare roles from two different guilds.")
# the @everyone role is always the lowest role in hierarchy
guild_id = self.guild.id
if self.id == guild_id:
# everyone_role < everyone_role -> False
return other.id != guild_id
if self.position < other.position:
return True
if self.position == other.position:
return int(self.id) > int(other.id)
return False
def __le__(self, other: Self) -> bool:
r = Role.__lt__(other, self)
if r is NotImplemented:
return NotImplemented
return not r
def __gt__(self, other: Self) -> bool:
return Role.__lt__(other, self)
def __ge__(self, other: Self) -> bool:
r = Role.__lt__(self, other)
if r is NotImplemented:
return NotImplemented
return not r
def _update(self, data: RolePayload) -> None:
self.name: str = data["name"]
self._permissions: int = int(data.get("permissions", 0))
self.position: int = data.get("position", 0)
self._colour: int = data.get("color", 0)
self.hoist: bool = data.get("hoist", False)
self.managed: bool = data.get("managed", False)
self.mentionable: bool = data.get("mentionable", False)
self._icon: Optional[str] = data.get("icon", None)
if self._icon is None:
self._icon: Optional[str] = data.get("unicode_emoji", None)
self.tags: Optional[RoleTags]
try:
self.tags = RoleTags(data["tags"])
except KeyError:
self.tags = None
self._flags: int = data.get("flags", 0)
def is_default(self) -> bool:
""":class:`bool`: Checks if the role is the default role."""
return self.guild.id == self.id
def is_bot_managed(self) -> bool:
""":class:`bool`: Whether the role is associated with a bot.
.. versionadded:: 1.6
"""
return self.tags is not None and self.tags.is_bot_managed()
def is_premium_subscriber(self) -> bool:
""":class:`bool`: Whether the role is the premium subscriber, AKA "boost", role for the guild.
.. versionadded:: 1.6
"""
return self.tags is not None and self.tags.is_premium_subscriber()
def is_integration(self) -> bool:
""":class:`bool`: Whether the role is managed by an integration.
.. versionadded:: 1.6
"""
return self.tags is not None and self.tags.is_integration()
def is_assignable(self) -> bool:
""":class:`bool`: Whether the role is able to be assigned or removed by the bot.
.. versionadded:: 2.0
"""
me = self.guild.me
return (
not self.is_default()
and not self.managed
and (me.top_role > self or me.id == self.guild.owner_id)
)
def is_in_prompt(self) -> bool:
""":class:`bool`: Whether the role can be selected in an onboarding prompt.
.. versionadded:: 2.6
"""
return self.flags.in_prompt
def permissions(self) -> Permissions:
""":class:`Permissions`: Returns the role's permissions."""
return Permissions(self._permissions)
def colour(self) -> Colour:
""":class:`Colour`: Returns the role colour. An alias exists under ``color``."""
return Colour(self._colour)
def color(self) -> Colour:
""":class:`Colour`: Returns the role color. An alias exists under ``colour``."""
return self.colour
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the role's creation time in UTC."""
return snowflake_time(self.id)
def mention(self) -> str:
""":class:`str`: Returns a string that allows you to mention a role."""
if self.id != self.guild.id:
return f"<@&{self.id}>"
return "@everyone"
def members(self) -> List[Member]:
"""List[:class:`Member`]: Returns all the members with this role."""
all_members = self.guild.members
if self.is_default():
return all_members
role_id = self.id
return [member for member in all_members if member._roles.has(role_id)]
def icon(self) -> Optional[Union[Asset, str]]:
"""Optional[Union[:class:`Asset`, :class:`str`]]: Returns the role's icon asset or its
unicode emoji, if available."""
if self._icon is None:
return None
if len(self._icon) == 1:
return self._icon
return Asset._from_icon(self._state, self.id, self._icon, "role")
async def _move(self, position: int, reason: Optional[str]) -> None:
if position <= 0:
raise InvalidArgument("Cannot move role to position 0 or below")
if self.is_default():
raise InvalidArgument("Cannot move default role")
if self.position == position:
return # Save discord the extra request.
http = self._state.http
change_range = range(min(self.position, position), max(self.position, position) + 1)
roles = [
r.id for r in self.guild.roles[1:] if r.position in change_range and r.id != self.id
]
if self.position > position:
roles.insert(0, self.id)
else:
roles.append(self.id)
payload: List[RolePositionUpdate] = [
{"id": z[0], "position": z[1]} for z in zip(roles, change_range)
]
await http.move_role_position(self.guild.id, payload, reason=reason)
async def edit(
self,
*,
name: str = MISSING,
permissions: Permissions = MISSING,
colour: Union[Colour, int] = MISSING,
color: Union[Colour, int] = MISSING,
hoist: bool = MISSING,
mentionable: bool = MISSING,
position: int = MISSING,
reason: Optional[str] = MISSING,
icon: Optional[Union[str, bytes, Asset, Attachment, File]] = MISSING,
) -> Optional[Role]:
"""|coro|
Edits the role.
You must have the :attr:`~Permissions.manage_roles` permission to
use this.
All fields are optional.
.. versionchanged:: 1.4
Can now pass ``int`` to ``colour`` keyword-only parameter.
.. versionchanged:: 2.0
Edits are no longer in-place, the newly edited role is returned instead.
.. versionchanged:: 2.1
The ``icon`` parameter now accepts :class:`Attachment`, and :class:`Asset`.
Parameters
----------
name: :class:`str`
The new role name to change to.
permissions: :class:`Permissions`
The new permissions to change to.
colour: Union[:class:`Colour`, :class:`int`]
The new colour to change to. (aliased to color as well)
hoist: :class:`bool`
Indicates if the role should be shown separately in the member list.
mentionable: :class:`bool`
Indicates if the role should be mentionable by others.
position: :class:`int`
The new role's position. This must be below your top role's
position or it will fail.
icon: Optional[Union[:class:`str`, :class:`bytes`, :class:`File`, :class:`Asset`, :class:`Attachment`]]
The role's icon image
reason: Optional[:class:`str`]
The reason for editing this role. Shows up on the audit log.
Raises
------
Forbidden
You do not have permissions to change the role.
HTTPException
Editing the role failed.
InvalidArgument
An invalid position was given or the default
role was asked to be moved.
Returns
-------
:class:`Role`
The newly edited role.
"""
if position is not MISSING:
await self._move(position, reason=reason)
payload: Dict[str, Any] = {}
if color is not MISSING:
colour = color
if colour is not MISSING:
if isinstance(colour, int):
payload["color"] = colour
else:
payload["color"] = colour.value
if name is not MISSING:
payload["name"] = name
if permissions is not MISSING:
payload["permissions"] = permissions.value
if hoist is not MISSING:
payload["hoist"] = hoist
if mentionable is not MISSING:
payload["mentionable"] = mentionable
if icon is not MISSING:
if isinstance(icon, str):
payload["unicode_emoji"] = icon
else:
payload["icon"] = await obj_to_base64_data(icon)
data = await self._state.http.edit_role(self.guild.id, self.id, reason=reason, **payload)
return Role(guild=self.guild, data=data, state=self._state)
async def delete(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Deletes the role.
You must have the :attr:`~Permissions.manage_roles` permission to
use this.
Parameters
----------
reason: Optional[:class:`str`]
The reason for deleting this role. Shows up on the audit log.
Raises
------
Forbidden
You do not have permissions to delete the role.
HTTPException
Deleting the role failed.
"""
await self._state.http.delete_role(self.guild.id, self.id, reason=reason)
def flags(self) -> RoleFlags:
""":class:`RoleFlags`: The avaliable flags the role has.
.. versionadded:: 2.6
"""
return RoleFlags._from_value(self._flags)
class Role(TypedDict):
id: Snowflake
name: str
color: int
hoist: bool
position: int
permissions: str
managed: bool
mentionable: bool
tags: NotRequired[RoleTags]
unicode_emoji: NotRequired[str]
icon: NotRequired[str]
flags: int
Snowflake = Union[str, int]
def _transform_role(
entry: AuditLogEntry, data: Optional[Snowflake]
) -> Optional[Union[Role, Object]]:
if data is None:
return None
role = entry.guild.get_role(int(data))
return role or Object(id=data) | null |
161,013 | from __future__ import annotations
import unicodedata
from typing import TYPE_CHECKING, List, Literal, Optional, Tuple, Type, Union
from .asset import Asset, AssetMixin
from .enums import StickerFormatType, StickerType, try_enum
from .errors import InvalidData
from .mixins import Hashable
from .utils import MISSING, cached_slot_property, find, get, snowflake_time
class Sticker(_StickerTag):
"""Represents a sticker.
.. versionadded:: 1.6
.. container:: operations
.. describe:: str(x)
Returns the name of the sticker.
.. describe:: x == y
Checks if the sticker is equal to another sticker.
.. describe:: x != y
Checks if the sticker is not equal to another sticker.
Attributes
----------
name: :class:`str`
The sticker's name.
id: :class:`int`
The id of the sticker.
description: :class:`str`
The description of the sticker.
pack_id: :class:`int`
The id of the sticker's pack.
format: :class:`StickerFormatType`
The format for the sticker's image.
url: :class:`str`
The URL for the sticker's image.
"""
__slots__ = ("_state", "id", "name", "description", "format", "url")
def __init__(self, *, state: ConnectionState, data: StickerPayload) -> None:
self._state: ConnectionState = state
self._from_data(data)
def _from_data(self, data: StickerPayload) -> None:
self.id: int = int(data["id"])
self.name: str = data["name"]
self.description: str = data["description"]
self.format: StickerFormatType = try_enum(StickerFormatType, data["format_type"])
self.url: str = f"{Asset.BASE}/stickers/{self.id}.{self.format.file_extension}"
def __repr__(self) -> str:
return f"<Sticker id={self.id} name={self.name!r}>"
def __str__(self) -> str:
return self.name
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: Returns the sticker's creation time in UTC."""
return snowflake_time(self.id)
class StandardSticker(Sticker):
"""Represents a sticker that is found in a standard sticker pack.
.. versionadded:: 2.0
.. container:: operations
.. describe:: str(x)
Returns the name of the sticker.
.. describe:: x == y
Checks if the sticker is equal to another sticker.
.. describe:: x != y
Checks if the sticker is not equal to another sticker.
Attributes
----------
name: :class:`str`
The sticker's name.
id: :class:`int`
The id of the sticker.
description: :class:`str`
The description of the sticker.
pack_id: :class:`int`
The id of the sticker's pack.
format: :class:`StickerFormatType`
The format for the sticker's image.
tags: List[:class:`str`]
A list of tags for the sticker.
sort_value: :class:`int`
The sticker's sort order within its pack.
"""
__slots__ = ("sort_value", "pack_id", "type", "tags")
def _from_data(self, data: StandardStickerPayload) -> None:
super()._from_data(data)
self.sort_value: int = data["sort_value"]
self.pack_id: int = int(data["pack_id"])
self.type: StickerType = StickerType.standard
try:
self.tags: List[str] = [tag.strip() for tag in data["tags"].split(",")]
except KeyError:
self.tags = []
def __repr__(self) -> str:
return f"<StandardSticker id={self.id} name={self.name!r} pack_id={self.pack_id}>"
async def pack(self) -> StickerPack:
"""|coro|
Retrieves the sticker pack that this sticker belongs to.
Raises
------
InvalidData
The corresponding sticker pack was not found.
HTTPException
Retrieving the sticker pack failed.
Returns
-------
:class:`StickerPack`
The retrieved sticker pack.
"""
data: ListPremiumStickerPacksPayload = await self._state.http.list_premium_sticker_packs()
packs = data["sticker_packs"]
pack = find(lambda d: int(d["id"]) == self.pack_id, packs)
if pack:
return StickerPack(state=self._state, data=pack)
raise InvalidData(f"Could not find corresponding sticker pack for {self!r}")
class GuildSticker(Sticker):
"""Represents a sticker that belongs to a guild.
.. versionadded:: 2.0
.. container:: operations
.. describe:: str(x)
Returns the name of the sticker.
.. describe:: x == y
Checks if the sticker is equal to another sticker.
.. describe:: x != y
Checks if the sticker is not equal to another sticker.
Attributes
----------
name: :class:`str`
The sticker's name.
id: :class:`int`
The id of the sticker.
description: :class:`str`
The description of the sticker.
format: :class:`StickerFormatType`
The format for the sticker's image.
available: :class:`bool`
Whether this sticker is available for use.
guild_id: :class:`int`
The ID of the guild that this sticker is from.
user: Optional[:class:`User`]
The user that created this sticker. This can only be retrieved using :meth:`Guild.fetch_sticker` and
having the :attr:`~Permissions.manage_emojis_and_stickers` permission.
emoji: :class:`str`
The name of a unicode emoji that represents this sticker.
"""
__slots__ = ("available", "guild_id", "user", "emoji", "type", "_cs_guild")
def _from_data(self, data: GuildStickerPayload) -> None:
super()._from_data(data)
self.available: bool = data["available"]
self.guild_id: int = int(data["guild_id"])
user = data.get("user")
self.user: Optional[User] = self._state.store_user(user) if user else None
self.emoji: str = data["tags"]
self.type: StickerType = StickerType.guild
def __repr__(self) -> str:
return f"<GuildSticker name={self.name!r} id={self.id} guild_id={self.guild_id} user={self.user!r}>"
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild that this sticker is from.
Could be ``None`` if the bot is not in the guild.
.. versionadded:: 2.0
"""
return self._state._get_guild(self.guild_id)
async def edit(
self,
*,
name: str = MISSING,
description: str = MISSING,
emoji: str = MISSING,
reason: Optional[str] = None,
) -> GuildSticker:
"""|coro|
Edits a :class:`GuildSticker` for the guild.
Parameters
----------
name: :class:`str`
The sticker's new name. Must be at least 2 characters.
description: Optional[:class:`str`]
The sticker's new description. Can be ``None``.
emoji: :class:`str`
The name of a unicode emoji that represents the sticker's expression.
reason: :class:`str`
The reason for editing this sticker. Shows up on the audit log.
Raises
------
Forbidden
You are not allowed to edit stickers.
HTTPException
An error occurred editing the sticker.
Returns
-------
:class:`GuildSticker`
The newly modified sticker.
"""
payload: EditGuildSticker = {}
if name is not MISSING:
payload["name"] = name
if description is not MISSING:
payload["description"] = description
if emoji is not MISSING:
try:
emoji = unicodedata.name(emoji)
except TypeError:
pass
else:
emoji = emoji.replace(" ", "_")
payload["tags"] = emoji
data: GuildStickerPayload = await self._state.http.modify_guild_sticker(
self.guild_id, self.id, payload, reason
)
return GuildSticker(state=self._state, data=data)
async def delete(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Deletes the custom :class:`Sticker` from the guild.
You must have :attr:`~Permissions.manage_emojis_and_stickers` permission to
do this.
Parameters
----------
reason: Optional[:class:`str`]
The reason for deleting this sticker. Shows up on the audit log.
Raises
------
Forbidden
You are not allowed to delete stickers.
HTTPException
An error occurred deleting the sticker.
"""
await self._state.http.delete_guild_sticker(self.guild_id, self.id, reason=reason)
class StickerType(IntEnum):
"""Represents the type of sticker.
.. versionadded:: 2.0
"""
standard = 1
"""Represents a standard sticker."""
guild = 2
"""Represents a custom sticker created in a guild."""
def try_enum(cls: Type[T], val: Any) -> T:
"""A function that tries to turn the value into enum ``cls``.
If it fails it returns a proxy invalid value instead.
"""
try:
return cls(val)
except ValueError:
return UnknownEnumValue(name=f"unknown_{val}", value=val) # type: ignore
class GuildSticker(BaseSticker):
type: Literal[2]
available: bool
guild_id: Snowflake
user: NotRequired[User]
def _sticker_factory(
sticker_type: Literal[1, 2]
) -> Tuple[Type[Union[StandardSticker, GuildSticker, Sticker]], StickerType]:
value = try_enum(StickerType, sticker_type)
if value == StickerType.standard:
return StandardSticker, value
if value == StickerType.guild:
return GuildSticker, value
return Sticker, value | null |
161,014 | from __future__ import annotations
import asyncio
import logging
import sys
import weakref
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Coroutine,
Dict,
Iterable,
List,
Literal,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
Union,
)
from urllib.parse import quote as _uriquote
import aiohttp
from . import __version__, utils
from .errors import (
DiscordServerError,
Forbidden,
GatewayNotFound,
HTTPException,
InvalidArgument,
LoginFailure,
NotFound,
)
from .file import File
from .gateway import DiscordClientWebSocketResponse
from .utils import MISSING
aiohttp.hdrs.WEBSOCKET = "websocket"
async def json_or_text(response: aiohttp.ClientResponse) -> Union[Dict[str, Any], str]:
text = await response.text(encoding="utf-8")
try:
if response.headers["content-type"] == "application/json":
return utils.from_json(text)
except KeyError:
# Thanks Cloudflare
pass
return text | null |
161,015 | from __future__ import annotations
import asyncio
import datetime
import time
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Literal,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
overload,
)
from . import abc, ui, utils
from .asset import Asset
from .emoji import Emoji
from .enums import (
ChannelType,
ForumLayoutType,
SortOrderType,
StagePrivacyLevel,
VideoQualityMode,
VoiceRegion,
try_enum,
)
from .errors import ClientException, InvalidArgument
from .file import File
from .flags import ChannelFlags, MessageFlags
from .iterators import ArchivedThreadIterator
from .mentions import AllowedMentions
from .mixins import Hashable, PinsMixin
from .object import Object
from .partial_emoji import PartialEmoji
from .permissions import PermissionOverwrite, Permissions
from .stage_instance import StageInstance
from .threads import Thread
from .utils import MISSING
class Message(Hashable):
r"""Represents a message from Discord.
.. container:: operations
.. describe:: x == y
Checks if two messages are equal.
.. describe:: x != y
Checks if two messages are not equal.
.. describe:: hash(x)
Returns the message's hash.
Attributes
----------
tts: :class:`bool`
Specifies if the message was done with text-to-speech.
This can only be accurately received in :func:`on_message` due to
a discord limitation.
type: :class:`MessageType`
The type of message. In most cases this should not be checked, but it is helpful
in cases where it might be a system message for :attr:`system_content`.
author: Union[:class:`Member`, :class:`abc.User`]
A :class:`Member` that sent the message. If :attr:`channel` is a
private channel or the user has the left the guild, then it is a :class:`User` instead.
content: :class:`str`
The actual contents of the message.
nonce: Optional[Union[:class:`str`, :class:`int`]]
The value used by the discord guild and the client to verify that the message is successfully sent.
This is not stored long term within Discord's servers and is only used ephemerally.
embeds: List[:class:`Embed`]
A list of embeds the message has.
channel: Union[:class:`TextChannel`, :class:`Thread`, :class:`DMChannel`, :class:`GroupChannel`, :class:`PartialMessageable`]
The :class:`TextChannel` or :class:`Thread` that the message was sent from.
Could be a :class:`DMChannel` or :class:`GroupChannel` if it's a private message.
reference: Optional[:class:`~nextcord.MessageReference`]
The message that this message references. This is only applicable to messages of
type :attr:`MessageType.pins_add`, crossposted messages created by a
followed channel integration, or message replies.
.. versionadded:: 1.5
mention_everyone: :class:`bool`
Specifies if the message mentions everyone.
.. note::
This does not check if the ``@everyone`` or the ``@here`` text is in the message itself.
Rather this boolean indicates if either the ``@everyone`` or the ``@here`` text is in the message
**and** it did end up mentioning.
mentions: List[:class:`abc.User`]
A list of :class:`Member` that were mentioned. If the message is in a private message
then the list will be of :class:`User` instead. For messages that are not of type
:attr:`MessageType.default`\, this array can be used to aid in system messages.
For more information, see :attr:`system_content`.
.. warning::
The order of the mentions list is not in any particular order so you should
not rely on it. This is a Discord limitation, not one with the library.
channel_mentions: List[:class:`abc.GuildChannel`]
A list of :class:`abc.GuildChannel` that were mentioned. If the message is in a private message
then the list is always empty.
role_mentions: List[:class:`Role`]
A list of :class:`Role` that were mentioned. If the message is in a private message
then the list is always empty.
id: :class:`int`
The message ID.
webhook_id: Optional[:class:`int`]
If this message was sent by a webhook, then this is the webhook ID's that sent this
message.
attachments: List[:class:`Attachment`]
A list of attachments given to a message.
pinned: :class:`bool`
Specifies if the message is currently pinned.
flags: :class:`MessageFlags`
Extra features of the message.
.. versionadded:: 1.3
reactions : List[:class:`Reaction`]
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
activity: Optional[:class:`dict`]
The activity associated with this message. Sent with Rich-Presence related messages that for
example, request joining, spectating, or listening to or with another member.
It is a dictionary with the following optional keys:
- ``type``: An integer denoting the type of message activity being requested.
- ``party_id``: The party ID associated with the party.
application: Optional[:class:`dict`]
The rich presence enabled application associated with this message.
It is a dictionary with the following keys:
- ``id``: A string representing the application's ID.
- ``name``: A string representing the application's name.
- ``description``: A string representing the application's description.
- ``icon``: A string representing the icon ID of the application.
- ``cover_image``: A string representing the embed's image asset ID.
stickers: List[:class:`StickerItem`]
A list of sticker items given to the message.
.. versionadded:: 1.6
components: List[:class:`Component`]
A list of components in the message.
.. versionadded:: 2.0
guild: Optional[:class:`Guild`]
The guild that the message belongs to, if applicable.
interaction: Optional[:class:`MessageInteraction`]
The interaction data of a message, if applicable.
"""
__slots__ = (
"_state",
"_edited_timestamp",
"_cs_channel_mentions",
"_cs_raw_mentions",
"_cs_clean_content",
"_cs_raw_channel_mentions",
"_cs_raw_role_mentions",
"_cs_system_content",
"tts",
"content",
"channel",
"webhook_id",
"mention_everyone",
"embeds",
"id",
"interaction",
"mentions",
"author",
"attachments",
"nonce",
"pinned",
"role_mentions",
"type",
"flags",
"reactions",
"reference",
"application",
"activity",
"stickers",
"components",
"_background_tasks",
"guild",
)
if TYPE_CHECKING:
_HANDLERS: ClassVar[List[Tuple[str, Callable[..., None]]]]
_CACHED_SLOTS: ClassVar[List[str]]
guild: Optional[Guild]
reference: Optional[MessageReference]
mentions: List[Union[User, Member]]
author: Union[User, Member]
role_mentions: List[Role]
def __init__(
self,
*,
state: ConnectionState,
channel: MessageableChannel,
data: MessagePayload,
) -> None:
self._state: ConnectionState = state
self.id: int = int(data["id"])
self.webhook_id: Optional[int] = utils.get_as_snowflake(data, "webhook_id")
self.reactions: List[Reaction] = [
Reaction(message=self, data=d) for d in data.get("reactions", [])
]
self.attachments: List[Attachment] = [
Attachment(data=a, state=self._state) for a in data["attachments"]
]
self.embeds: List[Embed] = [Embed.from_dict(a) for a in data["embeds"]]
self.application: Optional[MessageApplicationPayload] = data.get("application")
self.activity: Optional[MessageActivityPayload] = data.get("activity")
self.channel: MessageableChannel = channel
self._edited_timestamp: Optional[datetime.datetime] = utils.parse_time(
data["edited_timestamp"]
)
self.type: MessageType = try_enum(MessageType, data["type"])
self.pinned: bool = data["pinned"]
self.flags: MessageFlags = MessageFlags._from_value(data.get("flags", 0))
self.mention_everyone: bool = data["mention_everyone"]
self.tts: bool = data["tts"]
self.content: str = data["content"]
self.nonce: Optional[Union[int, str]] = data.get("nonce")
self.stickers: List[StickerItem] = [
StickerItem(data=d, state=state) for d in data.get("sticker_items", [])
]
self.components: List[Component] = [
_component_factory(d) for d in data.get("components", [])
]
self._background_tasks: Set[asyncio.Task[None]] = set()
try:
# if the channel doesn't have a guild attribute, we handle that
self.guild = channel.guild # type: ignore
except AttributeError:
if getattr(channel, "type", None) not in (ChannelType.group, ChannelType.private):
self.guild = state._get_guild(utils.get_as_snowflake(data, "guild_id"))
else:
self.guild = None
if (
(thread_data := data.get("thread"))
and not self.thread
and isinstance(self.guild, Guild)
):
self.guild._store_thread(thread_data)
try:
ref = data["message_reference"]
except KeyError:
self.reference = None
else:
self.reference = ref = MessageReference.with_state(state, ref)
try:
resolved = data["referenced_message"]
except KeyError:
pass
else:
if resolved is None:
ref.resolved = DeletedReferencedMessage(ref)
else:
# Right now the channel IDs match but maybe in the future they won't.
if ref.channel_id == channel.id:
chan = channel
else:
chan, _ = state._get_guild_channel(resolved)
# the channel will be the correct type here
ref.resolved = self.__class__(channel=chan, data=resolved, state=state) # type: ignore
for handler in ("author", "member", "mentions", "mention_roles"):
try:
getattr(self, f"_handle_{handler}")(data[handler])
except KeyError:
continue
self.interaction: Optional[MessageInteraction] = (
MessageInteraction(data=data["interaction"], guild=self.guild, state=self._state)
if "interaction" in data
else None
)
def __repr__(self) -> str:
name = self.__class__.__name__
return f"<{name} id={self.id} channel={self.channel!r} type={self.type!r} author={self.author!r} flags={self.flags!r}>"
def _try_patch(self, data, key, transform=None) -> None:
try:
value = data[key]
except KeyError:
pass
else:
if transform is None:
setattr(self, key, value)
else:
setattr(self, key, transform(value))
def _add_reaction(self, data, emoji: Emoji | PartialEmoji | str, user_id) -> Reaction:
finder: Callable[[Reaction], bool] = lambda r: r.emoji == emoji
reaction = utils.find(finder, self.reactions)
is_me = data["me"] = user_id == self._state.self_id
if reaction is None:
reaction = Reaction(message=self, data=data, emoji=emoji)
self.reactions.append(reaction)
else:
reaction.count += 1
if is_me:
reaction.me = is_me
return reaction
def _remove_reaction(
self, data: ReactionPayload, emoji: EmojiInputType, user_id: int
) -> Reaction:
reaction = utils.find(lambda r: r.emoji == emoji, self.reactions)
if reaction is None:
# already removed?
raise ValueError("Emoji already removed?")
# if reaction isn't in the list, we crash. This means discord
# sent bad data, or we stored improperly
reaction.count -= 1
if user_id == self._state.self_id:
reaction.me = False
if reaction.count == 0:
# this raises ValueError if something went wrong as well.
self.reactions.remove(reaction)
return reaction
def _clear_emoji(self, emoji) -> Optional[Reaction]:
to_check = str(emoji)
for index, reaction in enumerate(self.reactions): # noqa: B007
if str(reaction.emoji) == to_check:
break
else:
# didn't find anything so just return
return None
del self.reactions[index]
return reaction
def _update(self, data) -> None:
# In an update scheme, 'author' key has to be handled before 'member'
# otherwise they overwrite each other which is undesirable.
# Since there's no good way to do this we have to iterate over every
# handler rather than iterating over the keys which is a little slower
for key, handler in self._HANDLERS:
try:
value = data[key]
except KeyError:
continue
else:
handler(self, value)
# clear the cached properties
for attr in self._CACHED_SLOTS:
with contextlib.suppress(AttributeError):
delattr(self, attr)
def _handle_edited_timestamp(self, value: str) -> None:
self._edited_timestamp = utils.parse_time(value)
def _handle_pinned(self, value: bool) -> None:
self.pinned = value
def _handle_flags(self, value: int) -> None:
self.flags = MessageFlags._from_value(value)
def _handle_application(self, value: MessageApplicationPayload) -> None:
self.application = value
def _handle_activity(self, value: MessageActivityPayload) -> None:
self.activity = value
def _handle_mention_everyone(self, value: bool) -> None:
self.mention_everyone = value
def _handle_tts(self, value: bool) -> None:
self.tts = value
def _handle_type(self, value: int) -> None:
self.type = try_enum(MessageType, value)
def _handle_content(self, value: str) -> None:
self.content = value
def _handle_attachments(self, value: List[AttachmentPayload]) -> None:
self.attachments = [Attachment(data=a, state=self._state) for a in value]
def _handle_embeds(self, value: List[EmbedPayload]) -> None:
self.embeds = [Embed.from_dict(data) for data in value]
def _handle_nonce(self, value: Union[str, int]) -> None:
self.nonce = value
def _handle_author(self, author: UserPayload) -> None:
self.author = self._state.store_user(author)
if isinstance(self.guild, Guild):
found = self.guild.get_member(self.author.id)
if found is not None:
self.author = found
def _handle_member(self, member: MemberPayload) -> None:
# The gateway now gives us full Member objects sometimes with the following keys
# deaf, mute, joined_at, roles
# For the sake of performance I'm going to assume that the only
# field that needs *updating* would be the joined_at field.
# If there is no Member object (for some strange reason), then we can upgrade
# ourselves to a more "partial" member object.
author = self.author
try:
# Update member reference
author._update_from_message(member) # type: ignore
except AttributeError:
# It's a user here
# TODO: consider adding to cache here
self.author = Member._from_message(message=self, data=member)
def _handle_mentions(self, mentions: List[UserWithMemberPayload]) -> None:
self.mentions = r = []
guild = self.guild
state = self._state
if not isinstance(guild, Guild):
self.mentions = [state.store_user(m) for m in mentions]
return
for mention in filter(None, mentions):
id_search = int(mention["id"])
member = guild.get_member(id_search)
if member is not None:
r.append(member)
else:
r.append(Member._try_upgrade(data=mention, guild=guild, state=state))
def _handle_mention_roles(self, role_mentions: List[int]) -> None:
self.role_mentions = []
if isinstance(self.guild, Guild):
for role_id in map(int, role_mentions):
role = self.guild.get_role(role_id)
if role is not None:
self.role_mentions.append(role)
def _handle_components(self, components: List[ComponentPayload]) -> None:
self.components = [_component_factory(d) for d in components]
def _handle_thread(self, thread: Optional[ThreadPayload]) -> None:
if thread:
self.guild._store_thread(thread) # type: ignore
def _rebind_cached_references(
self, new_guild: Guild, new_channel: Union[TextChannel, Thread]
) -> None:
self.guild = new_guild
self.channel = new_channel
def raw_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of user IDs matched with
the syntax of ``<@user_id>`` in the message content.
This allows you to receive the user IDs of mentioned users
even in a private message context.
"""
return utils.parse_raw_mentions(self.content)
def raw_channel_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of channel IDs matched with
the syntax of ``<#channel_id>`` in the message content.
"""
return utils.parse_raw_channel_mentions(self.content)
def raw_role_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of role IDs matched with
the syntax of ``<@&role_id>`` in the message content.
"""
return utils.parse_raw_role_mentions(self.content)
def channel_mentions(self) -> List[GuildChannel]:
if self.guild is None:
return []
it = filter(None, map(self.guild.get_channel, self.raw_channel_mentions))
return utils.unique(it)
def clean_content(self) -> str:
""":class:`str`: A property that returns the content in a "cleaned up"
manner. This basically means that mentions are transformed
into the way the client shows it. e.g. ``<#id>`` will transform
into ``#name``.
This will also transform @everyone and @here mentions into
non-mentions.
.. note::
This *does not* affect markdown. If you want to escape
or remove markdown then use :func:`utils.escape_markdown` or :func:`utils.remove_markdown`
respectively, along with this function.
"""
transformations = {
re.escape(f"<#{channel.id}>"): "#" + channel.name for channel in self.channel_mentions
}
mention_transforms = {
re.escape(f"<@{member.id}>"): "@" + member.display_name for member in self.mentions
}
# add the <@!user_id> cases as well..
second_mention_transforms = {
re.escape(f"<@!{member.id}>"): "@" + member.display_name for member in self.mentions
}
transformations.update(mention_transforms)
transformations.update(second_mention_transforms)
if self.guild is not None:
role_transforms = {
re.escape(f"<@&{role.id}>"): "@" + role.name for role in self.role_mentions
}
transformations.update(role_transforms)
def repl(obj):
return transformations.get(re.escape(obj.group(0)), "")
pattern = re.compile("|".join(transformations.keys()))
result = pattern.sub(repl, self.content)
return escape_mentions(result)
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: The message's creation time in UTC."""
return utils.snowflake_time(self.id)
def edited_at(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: An aware UTC datetime object containing the edited time of the message."""
return self._edited_timestamp
def jump_url(self) -> str:
""":class:`str`: Returns a URL that allows the client to jump to this message."""
guild_id = getattr(self.guild, "id", "@me")
return f"https://discord.com/channels/{guild_id}/{self.channel.id}/{self.id}"
def thread(self) -> Optional[Thread]:
"""Optional[:class:`Thread`]: The thread started from this message. None if no thread was started."""
if not isinstance(self.guild, Guild):
return None
return self.guild.get_thread(self.id)
def is_system(self) -> bool:
""":class:`bool`: Whether the message is a system message.
A system message is a message that is constructed entirely by the Discord API
in response to something.
.. versionadded:: 1.3
"""
return self.type not in (
MessageType.default,
MessageType.reply,
MessageType.chat_input_command,
MessageType.context_menu_command,
MessageType.thread_starter_message,
)
def system_content(self):
r""":class:`str`: A property that returns the content that is rendered
regardless of the :attr:`Message.type`.
In the case of :attr:`MessageType.default` and :attr:`MessageType.reply`\,
this just returns the regular :attr:`Message.content`. Otherwise this
returns an English message denoting the contents of the system message.
"""
if self.type is MessageType.default:
return self.content
if self.type is MessageType.recipient_add:
if self.channel.type is ChannelType.group:
return f"{self.author.name} added {self.mentions[0].name} to the group."
return f"{self.author.name} added {self.mentions[0].name} to the thread."
if self.type is MessageType.recipient_remove:
if self.channel.type is ChannelType.group:
return f"{self.author.name} removed {self.mentions[0].name} from the group."
return f"{self.author.name} removed {self.mentions[0].name} from the thread."
if self.type is MessageType.channel_name_change:
return f"{self.author.name} changed the channel name: **{self.content}**"
if self.type is MessageType.channel_icon_change:
return f"{self.author.name} changed the channel icon."
if self.type is MessageType.pins_add:
return f"{self.author.name} pinned a message to this channel."
if self.type is MessageType.new_member:
formats = [
"{0} joined the party.",
"{0} is here.",
"Welcome, {0}. We hope you brought pizza.",
"A wild {0} appeared.",
"{0} just landed.",
"{0} just slid into the server.",
"{0} just showed up!",
"Welcome {0}. Say hi!",
"{0} hopped into the server.",
"Everyone welcome {0}!",
"Glad you're here, {0}.",
"Good to see you, {0}.",
"Yay you made it, {0}!",
]
created_at_ms = int(self.created_at.timestamp() * 1000)
return formats[created_at_ms % len(formats)].format(self.author.name)
if self.type is MessageType.premium_guild_subscription:
if not self.content:
return f"{self.author.name} just boosted the server!"
return f"{self.author.name} just boosted the server **{self.content}** times!"
if self.type is MessageType.premium_guild_tier_1:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 1!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 1!**"
if self.type is MessageType.premium_guild_tier_2:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 2!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 2!**"
if self.type is MessageType.premium_guild_tier_3:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 3!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 3!**"
if self.type is MessageType.channel_follow_add:
return f"{self.author.name} has added {self.content} to this channel"
if self.type is MessageType.guild_stream:
# the author will be a Member
return f"{self.author.name} is live! Now streaming {self.author.activity.name}" # type: ignore
if self.type is MessageType.guild_discovery_disqualified:
return "This server has been removed from Server Discovery because it no longer passes all the requirements. Check Server Settings for more details."
if self.type is MessageType.guild_discovery_requalified:
return "This server is eligible for Server Discovery again and has been automatically relisted!"
if self.type is MessageType.guild_discovery_grace_period_initial_warning:
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."
if self.type is MessageType.guild_discovery_grace_period_final_warning:
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."
if self.type is MessageType.thread_created:
return f"{self.author.name} started a thread: **{self.content}**. See all **threads**."
if self.type is MessageType.reply:
return self.content
if self.type is MessageType.thread_starter_message:
if self.reference is None or self.reference.resolved is None:
return "Sorry, we couldn't load the first message in this thread"
# the resolved message for the reference will be a Message
return self.reference.resolved.content # type: ignore
if self.type is MessageType.guild_invite_reminder:
return "Wondering who to invite?\nStart by inviting anyone who can help you build the server!"
if self.type is MessageType.stage_start:
return f"{self.author.display_name} started {self.content}"
if self.type is MessageType.stage_end:
return f"{self.author.display_name} ended {self.content}"
if self.type is MessageType.stage_speaker:
return f"{self.author.display_name} is now a speaker."
if self.type is MessageType.stage_topic:
return f"{self.author.display_name} changed the Stage topic: {self.content}"
return None
async def delete(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the message.
Your own messages could be deleted without any proper permissions. However to
delete other people's messages, you need the :attr:`~Permissions.manage_messages`
permission.
.. versionchanged:: 1.1
Added the new ``delay`` keyword-only parameter.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message. If the deletion fails then it is silently ignored.
Raises
------
Forbidden
You do not have proper permissions to delete the message.
NotFound
The message was deleted already
HTTPException
Deleting the message failed.
"""
if delay is not None:
async def delete(delay: float) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await self._state.http.delete_message(self.channel.id, self.id)
task = asyncio.create_task(delete(delay))
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await self._state.http.delete_message(self.channel.id, self.id)
async def edit(
self,
*,
content: Optional[str] = ...,
embed: Optional[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
file: Optional[File] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embeds: List[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
file: Optional[File] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embed: Optional[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
files: Optional[List[File]] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embeds: List[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
files: Optional[List[File]] = ...,
) -> Message:
...
async def edit(
self,
content: Optional[str] = MISSING,
embed: Optional[Embed] = MISSING,
embeds: List[Embed] = MISSING,
attachments: List[Attachment] = MISSING,
suppress: bool = MISSING,
delete_after: Optional[float] = None,
allowed_mentions: Optional[AllowedMentions] = MISSING,
view: Optional[View] = MISSING,
file: Optional[File] = MISSING,
files: Optional[List[File]] = MISSING,
) -> Message:
"""|coro|
Edits the message.
The content must be able to be transformed into a string via ``str(content)``.
.. versionchanged:: 1.3
The ``suppress`` keyword-only parameter was added.
Parameters
----------
content: Optional[:class:`str`]
The new content to replace the message with.
Could be ``None`` to remove the content.
embed: Optional[:class:`Embed`]
The new embed to replace the original with.
Could be ``None`` to remove the embed.
embeds: List[:class:`Embed`]
The new embeds to replace the original with. Must be a maximum of 10.
To remove all embeds ``[]`` should be passed.
.. versionadded:: 2.0
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep all existing attachments,
pass ``message.attachments``.
suppress: :class:`bool`
Whether to suppress embeds for the message. This removes
all the embeds if set to ``True``. If set to ``False``
this brings the embeds back if they were suppressed.
Using this parameter requires :attr:`~.Permissions.manage_messages`.
delete_after: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message we just edited. If the deletion fails,
then it is silently ignored.
allowed_mentions: Optional[:class:`~nextcord.AllowedMentions`]
Controls the mentions being processed in this message. If this is
passed, then the object is merged with :attr:`~nextcord.Client.allowed_mentions`.
The merging behaviour only overrides attributes that have been explicitly passed
to the object, otherwise it uses the attributes set in :attr:`~nextcord.Client.allowed_mentions`.
If no object is passed at all then the defaults given by :attr:`~nextcord.Client.allowed_mentions`
are used instead.
.. versionadded:: 1.4
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
file: Optional[:class:`File`]
If provided, a new file to add to the message.
.. versionadded:: 2.0
files: Optional[List[:class:`File`]]
If provided, a list of new files to add to the message.
.. versionadded:: 2.0
Raises
------
HTTPException
Editing the message failed.
Forbidden
Tried to suppress a message without permissions or
edited a message's content or embed that isn't yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
Returns
-------
:class:`Message`
The edited message.
"""
payload: Dict[str, Any] = {}
if content is not MISSING:
if content is not None:
payload["content"] = str(content)
else:
payload["content"] = None
if embed is not MISSING and embeds is not MISSING:
raise InvalidArgument("Cannot pass both embed and embeds parameter to edit()")
if file is not MISSING and files is not MISSING:
raise InvalidArgument("Cannot pass both file and files parameter to edit()")
if embed is not MISSING:
if embed is None:
payload["embeds"] = []
else:
payload["embeds"] = [embed.to_dict()]
elif embeds is not MISSING:
payload["embeds"] = [e.to_dict() for e in embeds]
if suppress is not MISSING:
flags = MessageFlags._from_value(self.flags.value)
flags.suppress_embeds = suppress
payload["flags"] = flags.value
if allowed_mentions is MISSING:
if self._state.allowed_mentions is not None and self.author.id == self._state.self_id:
payload["allowed_mentions"] = self._state.allowed_mentions.to_dict()
elif allowed_mentions is not None:
if self._state.allowed_mentions is not None:
payload["allowed_mentions"] = self._state.allowed_mentions.merge(
allowed_mentions
).to_dict()
else:
payload["allowed_mentions"] = allowed_mentions.to_dict()
if attachments is not MISSING:
payload["attachments"] = [a.to_dict() for a in attachments]
if view is not MISSING:
self._state.prevent_view_updates_for(self.id)
if view:
payload["components"] = view.to_components()
else:
payload["components"] = []
if file is not MISSING:
payload["files"] = [file]
elif files is not MISSING:
payload["files"] = files
data = await self._state.http.edit_message(self.channel.id, self.id, **payload)
message = Message(state=self._state, channel=self.channel, data=data)
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, self.id)
if delete_after is not None:
await self.delete(delay=delete_after)
return message
async def publish(self) -> None:
"""|coro|
Publishes this message to your announcement channel.
You must have the :attr:`~Permissions.send_messages` permission to do this.
If the message is not your own then the :attr:`~Permissions.manage_messages`
permission is also needed.
Raises
------
Forbidden
You do not have the proper permissions to publish this message.
HTTPException
Publishing the message failed.
"""
await self._state.http.publish_message(self.channel.id, self.id)
async def pin(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Pins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Parameters
----------
reason: Optional[:class:`str`]
The reason for pinning the message. Shows up on the audit log.
.. versionadded:: 1.4
Raises
------
Forbidden
You do not have permissions to pin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Pinning the message failed, probably due to the channel
having more than 50 pinned messages.
"""
await self._state.http.pin_message(self.channel.id, self.id, reason=reason)
self.pinned = True
async def unpin(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Unpins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Parameters
----------
reason: Optional[:class:`str`]
The reason for unpinning the message. Shows up on the audit log.
.. versionadded:: 1.4
Raises
------
Forbidden
You do not have permissions to unpin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Unpinning the message failed.
"""
await self._state.http.unpin_message(self.channel.id, self.id, reason=reason)
self.pinned = False
async def add_reaction(self, emoji: EmojiInputType) -> None:
"""|coro|
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You must have the :attr:`~Permissions.read_message_history` permission
to use this. If nobody else has reacted to the message using this
emoji, the :attr:`~Permissions.add_reactions` permission is required.
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to react with.
Raises
------
HTTPException
Adding the reaction failed.
Forbidden
You do not have the proper permissions to react to the message.
NotFound
The emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
await self._state.http.add_reaction(self.channel.id, self.id, emoji)
async def remove_reaction(
self, emoji: Union[EmojiInputType, Reaction], member: Snowflake
) -> None:
"""|coro|
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
If the reaction is not your own (i.e. ``member`` parameter is not you) then
the :attr:`~Permissions.manage_messages` permission is needed.
The ``member`` parameter must represent a member and meet
the :class:`abc.Snowflake` abc.
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to remove.
member: :class:`abc.Snowflake`
The member for which to remove the reaction.
Raises
------
HTTPException
Removing the reaction failed.
Forbidden
You do not have the proper permissions to remove the reaction.
NotFound
The member or emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
if member.id == self._state.self_id:
await self._state.http.remove_own_reaction(self.channel.id, self.id, emoji)
else:
await self._state.http.remove_reaction(self.channel.id, self.id, emoji, member.id)
async def clear_reaction(self, emoji: Union[EmojiInputType, Reaction]) -> None:
"""|coro|
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You need the :attr:`~Permissions.manage_messages` permission to use this.
.. versionadded:: 1.3
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to clear.
Raises
------
HTTPException
Clearing the reaction failed.
Forbidden
You do not have the proper permissions to clear the reaction.
NotFound
The emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
await self._state.http.clear_single_reaction(self.channel.id, self.id, emoji)
async def clear_reactions(self) -> None:
"""|coro|
Removes all the reactions from the message.
You need the :attr:`~Permissions.manage_messages` permission to use this.
Raises
------
HTTPException
Removing the reactions failed.
Forbidden
You do not have the proper permissions to remove all the reactions.
"""
await self._state.http.clear_reactions(self.channel.id, self.id)
async def create_thread(
self, *, name: str, auto_archive_duration: ThreadArchiveDuration = MISSING
) -> Thread:
"""|coro|
Creates a public thread from this message.
You must have :attr:`~nextcord.Permissions.create_public_threads` in order to
create a public thread from a message.
The channel this message belongs in must be a :class:`TextChannel`.
.. versionadded:: 2.0
Parameters
----------
name: :class:`str`
The name of the thread.
auto_archive_duration: :class:`int`
The duration in minutes before a thread is automatically archived for inactivity.
If not provided, the channel's default auto archive duration is used.
Raises
------
Forbidden
You do not have permissions to create a thread.
HTTPException
Creating the thread failed.
InvalidArgument
This message does not have guild info attached.
Returns
-------
:class:`.Thread`
The created thread.
"""
if self.guild is None:
raise InvalidArgument("This message does not have guild info attached.")
default_auto_archive_duration: ThreadArchiveDuration = getattr(
self.channel, "default_auto_archive_duration", 1440
)
data = await self._state.http.start_thread_with_message(
self.channel.id,
self.id,
name=name,
auto_archive_duration=auto_archive_duration or default_auto_archive_duration,
)
return Thread(guild=self.guild, state=self._state, data=data)
async def reply(self, content: Optional[str] = None, **kwargs) -> Message:
"""|coro|
A shortcut method to :meth:`.abc.Messageable.send` to reply to the
:class:`.Message`.
.. versionadded:: 1.6
Raises
------
~nextcord.HTTPException
Sending the message failed.
~nextcord.Forbidden
You do not have the proper permissions to send the message.
~nextcord.InvalidArgument
The ``files`` list is not of the appropriate size or
you specified both ``file`` and ``files``.
Returns
-------
:class:`.Message`
The message that was sent.
"""
return await self.channel.send(content, reference=self, **kwargs)
def to_reference(self, *, fail_if_not_exists: bool = True) -> MessageReference:
"""Creates a :class:`~nextcord.MessageReference` from the current message.
.. versionadded:: 1.6
Parameters
----------
fail_if_not_exists: :class:`bool`
Whether replying using the message reference should raise :class:`HTTPException`
if the message no longer exists or Discord could not fetch the message.
.. versionadded:: 1.7
Returns
-------
:class:`~nextcord.MessageReference`
The reference to this message.
"""
return MessageReference.from_message(self, fail_if_not_exists=fail_if_not_exists)
def to_message_reference_dict(self) -> MessageReferencePayload:
data: MessageReferencePayload = {
"message_id": self.id,
"channel_id": self.channel.id,
}
if self.guild is not None:
data["guild_id"] = self.guild.id
return data
async def _single_delete_strategy(messages: Iterable[Message]) -> None:
for m in messages:
await m.delete() | null |
161,016 | from __future__ import annotations
import asyncio
import datetime
import time
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Literal,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
overload,
)
from . import abc, ui, utils
from .asset import Asset
from .emoji import Emoji
from .enums import (
ChannelType,
ForumLayoutType,
SortOrderType,
StagePrivacyLevel,
VideoQualityMode,
VoiceRegion,
try_enum,
)
from .errors import ClientException, InvalidArgument
from .file import File
from .flags import ChannelFlags, MessageFlags
from .iterators import ArchivedThreadIterator
from .mentions import AllowedMentions
from .mixins import Hashable, PinsMixin
from .object import Object
from .partial_emoji import PartialEmoji
from .permissions import PermissionOverwrite, Permissions
from .stage_instance import StageInstance
from .threads import Thread
from .utils import MISSING
def _channel_factory(channel_type: int):
cls, value = _guild_channel_factory(channel_type)
if value is ChannelType.private:
return DMChannel, value
if value is ChannelType.group:
return GroupChannel, value
return cls, value
class ChannelType(IntEnum):
"""Specifies the type of channel."""
text = 0
"""A text channel"""
private = 1
"""A private text channel. Also called a direct message."""
voice = 2
"""A voice channel"""
group = 3
"""A private group text channel."""
category = 4
"""A category channel."""
news = 5
"""A guild news channel."""
news_thread = 10
"""A news thread."""
public_thread = 11
"""A public thread."""
private_thread = 12
"""A private thread."""
stage_voice = 13
"""A guild stage voice channel."""
guild_directory = 14
"""A channel containing the guilds in a
`Student Hub <https://support.discord.com/hc/en-us/articles/4406046651927-Discord-Student-Hubs-FAQ>`_
"""
forum = 15
"""A forum channel."""
def __str__(self) -> str:
return self.name
class Thread(Messageable, Hashable, PinsMixin):
"""Represents a Discord thread.
.. container:: operations
.. describe:: x == y
Checks if two threads are equal.
.. describe:: x != y
Checks if two threads are not equal.
.. describe:: hash(x)
Returns the thread's hash.
.. describe:: str(x)
Returns the thread's name.
.. versionadded:: 2.0
Attributes
----------
name: :class:`str`
The thread name.
guild: :class:`Guild`
The guild the thread belongs to.
id: :class:`int`
The thread ID.
parent_id: :class:`int`
The parent :class:`TextChannel` ID this thread belongs to.
owner_id: :class:`int`
The user's ID that created this thread.
last_message_id: Optional[:class:`int`]
The last message ID of the message sent to this thread. It may
*not* point to an existing or valid message.
slowmode_delay: :class:`int`
The number of seconds a member must wait between sending messages
in this thread. A value of ``0`` denotes that it is disabled.
Bots and users with :attr:`~Permissions.manage_channels` or
:attr:`~Permissions.manage_messages` bypass slowmode.
message_count: :class:`int`
An approximate number of messages in this thread. This caps at 50.
member_count: :class:`int`
An approximate number of members in this thread. This caps at 50.
me: Optional[:class:`ThreadMember`]
A thread member representing yourself, if you've joined the thread.
This could not be available.
archived: :class:`bool`
Whether the thread is archived.
locked: :class:`bool`
Whether the thread is locked.
invitable: :class:`bool`
Whether non-moderators can add other non-moderators to this thread.
This is always ``True`` for public threads.
archiver_id: Optional[:class:`int`]
The user's ID that archived this thread.
auto_archive_duration: :class:`int`
The duration in minutes until the thread is automatically archived due to inactivity.
Usually a value of 60, 1440, 4320 and 10080.
archive_timestamp: :class:`datetime.datetime`
An aware timestamp of when the thread's archived status was last updated in UTC.
create_timestamp: Optional[:class:`datetime.datetime`]
Returns the threads's creation time in UTC.
This is ``None`` if the thread was created before January 9th, 2021.
.. versionadded:: 2.0
applied_tag_ids: List[:class:`int`]
A list of tag IDs that have been applied to this thread.
.. versionadded:: 2.4
"""
__slots__ = (
"name",
"id",
"guild",
"_type",
"_state",
"_members",
"owner_id",
"parent_id",
"last_message_id",
"message_count",
"member_count",
"slowmode_delay",
"me",
"locked",
"archived",
"invitable",
"archiver_id",
"auto_archive_duration",
"archive_timestamp",
"create_timestamp",
"flags",
"applied_tag_ids",
)
def __init__(self, *, guild: Guild, state: ConnectionState, data: ThreadPayload) -> None:
self._state: ConnectionState = state
self.guild = guild
self._members: Dict[int, ThreadMember] = {}
self._from_data(data)
async def _get_channel(self):
return self
def __repr__(self) -> str:
return (
f"<Thread id={self.id!r} name={self.name!r} parent={self.parent}"
f" owner_id={self.owner_id!r} locked={self.locked} archived={self.archived}>"
)
def __str__(self) -> str:
return self.name
def _from_data(self, data: ThreadPayload) -> None:
self.id = int(data["id"])
self.parent_id = int(data["parent_id"])
self.owner_id = int(data["owner_id"])
self.name = data["name"]
self._type = try_enum(ChannelType, data["type"])
self.last_message_id = get_as_snowflake(data, "last_message_id")
self.slowmode_delay = data.get("rate_limit_per_user", 0)
self.message_count = data["message_count"]
self.member_count = data["member_count"]
self._unroll_metadata(data["thread_metadata"])
self.flags: ChannelFlags = ChannelFlags._from_value(data.get("flags", 0))
try:
member = data["member"]
except KeyError:
self.me = None
else:
self.me = ThreadMember(self, member)
self.applied_tag_ids: List[int] = [int(tag_id) for tag_id in data.get("applied_tags", [])]
def _unroll_metadata(self, data: ThreadMetadata) -> None:
self.archived = data["archived"]
self.archiver_id = get_as_snowflake(data, "archiver_id")
self.auto_archive_duration = data["auto_archive_duration"]
self.archive_timestamp = parse_time(data["archive_timestamp"])
self.locked = data.get("locked", False)
self.invitable = data.get("invitable", True)
self.create_timestamp = parse_time(data.get("create_timestamp"))
def _update(self, data) -> None:
with contextlib.suppress(KeyError):
self.name = data["name"]
self.slowmode_delay = data.get("rate_limit_per_user", 0)
self.flags: ChannelFlags = ChannelFlags._from_value(data.get("flags", 0))
self.applied_tag_ids: List[int] = [int(tag_id) for tag_id in data.get("applied_tags", [])]
with contextlib.suppress(KeyError):
self._unroll_metadata(data["thread_metadata"])
def created_at(self) -> Optional[datetime]:
"""Optional[:class:`datetime.datetime`]: Returns the threads's creation time in UTC.
This is ``None`` if the thread was created before January 9th, 2021.
.. versionadded:: 2.0
"""
return self.create_timestamp
def type(self) -> ChannelType:
""":class:`ChannelType`: The channel's Discord type."""
return self._type
def parent(self) -> Optional[Union[TextChannel, ForumChannel]]:
"""Optional[Union[:class:`TextChannel`, :class:`ForumChannel`]]: The parent channel this thread belongs to."""
return self.guild.get_channel(self.parent_id) # type: ignore
def owner(self) -> Optional[Member]:
"""Optional[:class:`Member`]: The member this thread belongs to."""
return self.guild.get_member(self.owner_id)
def mention(self) -> str:
""":class:`str`: The string that allows you to mention the thread."""
return f"<#{self.id}>"
def members(self) -> List[ThreadMember]:
"""List[:class:`ThreadMember`]: A list of thread members in this thread.
This requires :attr:`Intents.members` to be properly filled. Most of the time however,
this data is not provided by the gateway and a call to :meth:`fetch_members` is
needed.
"""
return list(self._members.values())
def last_message(self) -> Optional[Message]:
"""Fetches the last message from this channel in cache.
The message might not be valid or point to an existing message.
.. admonition:: Reliable Fetching
:class: helpful
For a slightly more reliable method of fetching the
last message, consider using either :meth:`history`
or :meth:`fetch_message` with the :attr:`last_message_id`
attribute.
Returns
-------
Optional[:class:`Message`]
The last message in this channel or ``None`` if not found.
"""
return self._state._get_message(self.last_message_id) if self.last_message_id else None
def category(self) -> Optional[CategoryChannel]:
"""The category channel the parent channel belongs to, if applicable.
Raises
------
ClientException
The parent channel was not cached and returned ``None``.
Returns
-------
Optional[:class:`CategoryChannel`]
The parent channel's category.
"""
parent = self.parent
if parent is None:
raise ClientException("Parent channel not found")
return parent.category
def category_id(self) -> Optional[int]:
"""The category channel ID the parent channel belongs to, if applicable.
Raises
------
ClientException
The parent channel was not cached and returned ``None``.
Returns
-------
Optional[:class:`int`]
The parent channel's category ID.
"""
parent = self.parent
if parent is None:
raise ClientException("Parent channel not found")
return parent.category_id
def jump_url(self) -> str:
""":class:`str`: Returns a URL that allows the client to jump to this channel.
.. versionadded:: 2.0
"""
return f"https://discord.com/channels/{self.guild.id}/{self.id}"
def applied_tags(self) -> Optional[List[ForumTag]]:
"""Optional[List[:class:`ForumTag`]]: A list of tags applied to this thread.
This is ``None`` if the parent channel was not found in cache.
.. versionadded:: 2.4
"""
if self.parent is None:
return None
parent = self.parent
if not isinstance(parent, channel.ForumChannel):
return None
tags: List[ForumTag] = []
for tag_id in self.applied_tag_ids:
tag = parent.get_tag(tag_id)
if tag is not None:
tags.append(tag)
return tags
def is_private(self) -> bool:
""":class:`bool`: Whether the thread is a private thread.
A private thread is only viewable by those that have been explicitly
invited or have :attr:`~.Permissions.manage_threads`.
"""
return self._type is ChannelType.private_thread
def is_news(self) -> bool:
""":class:`bool`: Whether the thread is a news thread.
A news thread is a thread that has a parent that is a news channel,
i.e. :meth:`.TextChannel.is_news` is ``True``.
"""
return self._type is ChannelType.news_thread
def is_nsfw(self) -> bool:
""":class:`bool`: Whether the thread is NSFW or not.
An NSFW thread is a thread that has a parent that is an NSFW channel,
i.e. :meth:`.TextChannel.is_nsfw` is ``True``.
"""
parent = self.parent
return parent is not None and parent.is_nsfw()
def permissions_for(self, obj: Union[Member, Role], /) -> Permissions:
"""Handles permission resolution for the :class:`~nextcord.Member`
or :class:`~nextcord.Role`.
Since threads do not have their own permissions, they inherit them
from the parent channel. This is a convenience method for
calling :meth:`~nextcord.TextChannel.permissions_for` on the
parent channel.
Parameters
----------
obj: Union[:class:`~nextcord.Member`, :class:`~nextcord.Role`]
The object to resolve permissions for. This could be either
a member or a role. If it's a role then member overwrites
are not computed.
Raises
------
ClientException
The parent channel was not cached and returned ``None``
Returns
-------
:class:`~nextcord.Permissions`
The resolved permissions for the member or role.
"""
parent = self.parent
if parent is None:
raise ClientException("Parent channel not found")
return parent.permissions_for(obj)
async def delete_messages(self, messages: Iterable[Snowflake]) -> None:
"""|coro|
Deletes a list of messages. This is similar to :meth:`Message.delete`
except it bulk deletes multiple messages.
As a special case, if the number of messages is 0, then nothing
is done. If the number of messages is 1 then single message
delete is done. If it's more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that
are older than 14 days old.
You must have the :attr:`~Permissions.manage_messages` permission to
use this.
Usable only by bot accounts.
Parameters
----------
messages: Iterable[:class:`abc.Snowflake`]
An iterable of messages denoting which ones to bulk delete.
Raises
------
ClientException
The number of messages to delete was more than 100.
Forbidden
You do not have proper permissions to delete the messages or
you're not using a bot account.
NotFound
If single delete, then the message was already deleted.
HTTPException
Deleting the messages failed.
"""
if not isinstance(messages, (list, tuple)):
messages = list(messages)
if len(messages) == 0:
return # do nothing
if len(messages) == 1:
message_id = messages[0].id
await self._state.http.delete_message(self.id, message_id)
return
if len(messages) > 100:
raise ClientException("Can only bulk delete messages up to 100 messages")
message_ids: SnowflakeList = [m.id for m in messages]
await self._state.http.delete_messages(self.id, message_ids)
async def purge(
self,
*,
limit: Optional[int] = 100,
check: Callable[[Message], bool] = MISSING,
before: Optional[SnowflakeTime] = None,
after: Optional[SnowflakeTime] = None,
around: Optional[SnowflakeTime] = None,
oldest_first: Optional[bool] = False,
bulk: bool = True,
) -> List[Message]:
"""|coro|
Purges a list of messages that meet the criteria given by the predicate
``check``. If a ``check`` is not provided then all messages are deleted
without discrimination.
You must have the :attr:`~Permissions.manage_messages` permission to
delete messages even if they are your own (unless you are a user
account). The :attr:`~Permissions.read_message_history` permission is
also needed to retrieve message history.
Examples
--------
Deleting bot's messages ::
def is_me(m):
return m.author == client.user
deleted = await thread.purge(limit=100, check=is_me)
await thread.send(f'Deleted {len(deleted)} message(s)')
Parameters
----------
limit: Optional[:class:`int`]
The number of messages to search through. This is not the number
of messages that will be deleted, though it can be.
check: Callable[[:class:`Message`], :class:`bool`]
The function used to check if a message should be deleted.
It must take a :class:`Message` as its sole parameter.
before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]]
Same as ``before`` in :meth:`history`.
after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]]
Same as ``after`` in :meth:`history`.
around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]]
Same as ``around`` in :meth:`history`.
oldest_first: Optional[:class:`bool`]
Same as ``oldest_first`` in :meth:`history`.
bulk: :class:`bool`
If ``True``, use bulk delete. Setting this to ``False`` is useful for mass-deleting
a bot's own messages without :attr:`Permissions.manage_messages`. When ``True``, will
fall back to single delete if messages are older than two weeks.
Raises
------
Forbidden
You do not have proper permissions to do the actions required.
HTTPException
Purging the messages failed.
Returns
-------
List[:class:`.Message`]
The list of messages that were deleted.
"""
if check is MISSING:
check = lambda _: True
iterator = self.history(
limit=limit, before=before, after=after, oldest_first=oldest_first, around=around
)
ret: List[Message] = []
count = 0
minimum_time = int((time.time() - 14 * 24 * 60 * 60) * 1000.0 - 1420070400000) << 22
async def _single_delete_strategy(messages: Iterable[Message]) -> None:
for m in messages:
await m.delete()
strategy = self.delete_messages if bulk else _single_delete_strategy
async for message in iterator:
if count == 100:
to_delete = ret[-100:]
await strategy(to_delete)
count = 0
await asyncio.sleep(1)
if not check(message):
continue
if message.id < minimum_time:
# older than 14 days old
if count == 1:
await ret[-1].delete()
elif count >= 2:
to_delete = ret[-count:]
await strategy(to_delete)
count = 0
strategy = _single_delete_strategy
count += 1
ret.append(message)
# SOme messages remaining to poll
if count >= 2:
# more than 2 messages -> bulk delete
to_delete = ret[-count:]
await strategy(to_delete)
elif count == 1:
# delete a single message
await ret[-1].delete()
return ret
async def edit(
self,
*,
name: str = MISSING,
archived: bool = MISSING,
locked: bool = MISSING,
invitable: bool = MISSING,
slowmode_delay: int = MISSING,
auto_archive_duration: ThreadArchiveDuration = MISSING,
flags: ChannelFlags = MISSING,
applied_tags: List[ForumTag] = MISSING,
) -> Thread:
"""|coro|
Edits the thread.
Editing the thread requires :attr:`.Permissions.manage_threads`. The thread
creator can also edit ``name``, ``archived`` or ``auto_archive_duration``.
Note that if the thread is locked then only those with :attr:`.Permissions.manage_threads`
can unarchive a thread.
The thread must be unarchived to be edited.
Parameters
----------
name: :class:`str`
The new name of the thread.
archived: :class:`bool`
Whether to archive the thread or not.
locked: :class:`bool`
Whether to lock the thread or not.
invitable: :class:`bool`
Whether non-moderators can add other non-moderators to this thread.
Only available for private threads.
auto_archive_duration: :class:`int`
The new duration in minutes before a thread is automatically archived for inactivity.
Must be one of ``60``, ``1440``, ``4320``, or ``10080``.
slowmode_delay: :class:`int`
Specifies the slowmode rate limit for user in this thread, in seconds.
A value of ``0`` disables slowmode. The maximum value possible is ``21600``.
flags: :class:`ChannelFlags`
The new channel flags to use for this thread.
.. versionadded:: 2.1
applied_tags: List[:class:`ForumTag`]
The new tags to apply to this thread.
.. versionadded:: 2.4
Raises
------
Forbidden
You do not have permissions to edit the thread.
HTTPException
Editing the thread failed.
Returns
-------
:class:`Thread`
The newly edited thread.
"""
payload = {}
if name is not MISSING:
payload["name"] = str(name)
if archived is not MISSING:
payload["archived"] = archived
if auto_archive_duration is not MISSING:
payload["auto_archive_duration"] = auto_archive_duration
if locked is not MISSING:
payload["locked"] = locked
if invitable is not MISSING:
payload["invitable"] = invitable
if slowmode_delay is not MISSING:
payload["rate_limit_per_user"] = slowmode_delay
if flags is not MISSING:
payload["flags"] = flags.value
if applied_tags is not MISSING:
payload["applied_tags"] = [tag.id for tag in applied_tags]
data = await self._state.http.edit_channel(self.id, **payload)
# The data payload will always be a Thread payload
return Thread(data=data, state=self._state, guild=self.guild) # type: ignore
async def join(self) -> None:
"""|coro|
Joins this thread.
You must have :attr:`~Permissions.send_messages_in_threads` to join a thread.
If the thread is private, :attr:`~Permissions.manage_threads` is also needed.
Raises
------
Forbidden
You do not have permissions to join the thread.
HTTPException
Joining the thread failed.
"""
await self._state.http.join_thread(self.id)
async def leave(self) -> None:
"""|coro|
Leaves this thread.
Raises
------
HTTPException
Leaving the thread failed.
"""
await self._state.http.leave_thread(self.id)
async def add_user(self, user: Snowflake) -> None:
"""|coro|
Adds a user to this thread.
You must have :attr:`~Permissions.send_messages` and :attr:`~Permissions.use_threads`
to add a user to a public thread. If the thread is private then :attr:`~Permissions.send_messages`
and either :attr:`~Permissions.use_private_threads` or :attr:`~Permissions.manage_messages`
is required to add a user to the thread.
Parameters
----------
user: :class:`abc.Snowflake`
The user to add to the thread.
Raises
------
Forbidden
You do not have permissions to add the user to the thread.
HTTPException
Adding the user to the thread failed.
"""
await self._state.http.add_user_to_thread(self.id, user.id)
async def remove_user(self, user: Snowflake) -> None:
"""|coro|
Removes a user from this thread.
You must have :attr:`~Permissions.manage_threads` or be the creator of the thread to remove a user.
Parameters
----------
user: :class:`abc.Snowflake`
The user to add to the thread.
Raises
------
Forbidden
You do not have permissions to remove the user from the thread.
HTTPException
Removing the user from the thread failed.
"""
await self._state.http.remove_user_from_thread(self.id, user.id)
async def fetch_members(self) -> List[ThreadMember]:
"""|coro|
Retrieves all :class:`ThreadMember` that are in this thread.
This requires :attr:`Intents.members` to get information about members
other than yourself.
Raises
------
HTTPException
Retrieving the members failed.
Returns
-------
List[:class:`ThreadMember`]
All thread members in the thread.
"""
members = await self._state.http.get_thread_members(self.id)
return [ThreadMember(parent=self, data=data) for data in members]
async def delete(self) -> None:
"""|coro|
Deletes this thread.
You must have :attr:`~Permissions.manage_threads` to delete threads.
Raises
------
Forbidden
You do not have permissions to delete this thread.
HTTPException
Deleting the thread failed.
"""
await self._state.http.delete_channel(self.id)
def get_partial_message(self, message_id: int, /) -> PartialMessage:
"""Creates a :class:`PartialMessage` from the message ID.
This is useful if you want to work with a message and only have its ID without
doing an unnecessary API call.
.. versionadded:: 2.0
Parameters
----------
message_id: :class:`int`
The message ID to create a partial message for.
Returns
-------
:class:`PartialMessage`
The partial message.
"""
from .message import PartialMessage
return PartialMessage(channel=self, id=message_id)
def _add_member(self, member: ThreadMember) -> None:
self._members[member.id] = member
def _pop_member(self, member_id: int) -> Optional[ThreadMember]:
return self._members.pop(member_id, None)
def _threaded_channel_factory(channel_type: int):
cls, value = _channel_factory(channel_type)
if value in (ChannelType.private_thread, ChannelType.public_thread, ChannelType.news_thread):
return Thread, value
return cls, value | null |
161,017 | from __future__ import annotations
import asyncio
import datetime
import time
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Literal,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
overload,
)
from . import abc, ui, utils
from .asset import Asset
from .emoji import Emoji
from .enums import (
ChannelType,
ForumLayoutType,
SortOrderType,
StagePrivacyLevel,
VideoQualityMode,
VoiceRegion,
try_enum,
)
from .errors import ClientException, InvalidArgument
from .file import File
from .flags import ChannelFlags, MessageFlags
from .iterators import ArchivedThreadIterator
from .mentions import AllowedMentions
from .mixins import Hashable, PinsMixin
from .object import Object
from .partial_emoji import PartialEmoji
from .permissions import PermissionOverwrite, Permissions
from .stage_instance import StageInstance
from .threads import Thread
from .utils import MISSING
def _guild_channel_factory(channel_type: int):
value = try_enum(ChannelType, channel_type)
if value is ChannelType.text:
return TextChannel, value
if value is ChannelType.voice:
return VoiceChannel, value
if value is ChannelType.category:
return CategoryChannel, value
if value is ChannelType.news:
return TextChannel, value
if value is ChannelType.stage_voice:
return StageChannel, value
if value is ChannelType.forum:
return ForumChannel, value
return None, value
class ChannelType(IntEnum):
"""Specifies the type of channel."""
text = 0
"""A text channel"""
private = 1
"""A private text channel. Also called a direct message."""
voice = 2
"""A voice channel"""
group = 3
"""A private group text channel."""
category = 4
"""A category channel."""
news = 5
"""A guild news channel."""
news_thread = 10
"""A news thread."""
public_thread = 11
"""A public thread."""
private_thread = 12
"""A private thread."""
stage_voice = 13
"""A guild stage voice channel."""
guild_directory = 14
"""A channel containing the guilds in a
`Student Hub <https://support.discord.com/hc/en-us/articles/4406046651927-Discord-Student-Hubs-FAQ>`_
"""
forum = 15
"""A forum channel."""
def __str__(self) -> str:
return self.name
class Thread(Messageable, Hashable, PinsMixin):
"""Represents a Discord thread.
.. container:: operations
.. describe:: x == y
Checks if two threads are equal.
.. describe:: x != y
Checks if two threads are not equal.
.. describe:: hash(x)
Returns the thread's hash.
.. describe:: str(x)
Returns the thread's name.
.. versionadded:: 2.0
Attributes
----------
name: :class:`str`
The thread name.
guild: :class:`Guild`
The guild the thread belongs to.
id: :class:`int`
The thread ID.
parent_id: :class:`int`
The parent :class:`TextChannel` ID this thread belongs to.
owner_id: :class:`int`
The user's ID that created this thread.
last_message_id: Optional[:class:`int`]
The last message ID of the message sent to this thread. It may
*not* point to an existing or valid message.
slowmode_delay: :class:`int`
The number of seconds a member must wait between sending messages
in this thread. A value of ``0`` denotes that it is disabled.
Bots and users with :attr:`~Permissions.manage_channels` or
:attr:`~Permissions.manage_messages` bypass slowmode.
message_count: :class:`int`
An approximate number of messages in this thread. This caps at 50.
member_count: :class:`int`
An approximate number of members in this thread. This caps at 50.
me: Optional[:class:`ThreadMember`]
A thread member representing yourself, if you've joined the thread.
This could not be available.
archived: :class:`bool`
Whether the thread is archived.
locked: :class:`bool`
Whether the thread is locked.
invitable: :class:`bool`
Whether non-moderators can add other non-moderators to this thread.
This is always ``True`` for public threads.
archiver_id: Optional[:class:`int`]
The user's ID that archived this thread.
auto_archive_duration: :class:`int`
The duration in minutes until the thread is automatically archived due to inactivity.
Usually a value of 60, 1440, 4320 and 10080.
archive_timestamp: :class:`datetime.datetime`
An aware timestamp of when the thread's archived status was last updated in UTC.
create_timestamp: Optional[:class:`datetime.datetime`]
Returns the threads's creation time in UTC.
This is ``None`` if the thread was created before January 9th, 2021.
.. versionadded:: 2.0
applied_tag_ids: List[:class:`int`]
A list of tag IDs that have been applied to this thread.
.. versionadded:: 2.4
"""
__slots__ = (
"name",
"id",
"guild",
"_type",
"_state",
"_members",
"owner_id",
"parent_id",
"last_message_id",
"message_count",
"member_count",
"slowmode_delay",
"me",
"locked",
"archived",
"invitable",
"archiver_id",
"auto_archive_duration",
"archive_timestamp",
"create_timestamp",
"flags",
"applied_tag_ids",
)
def __init__(self, *, guild: Guild, state: ConnectionState, data: ThreadPayload) -> None:
self._state: ConnectionState = state
self.guild = guild
self._members: Dict[int, ThreadMember] = {}
self._from_data(data)
async def _get_channel(self):
return self
def __repr__(self) -> str:
return (
f"<Thread id={self.id!r} name={self.name!r} parent={self.parent}"
f" owner_id={self.owner_id!r} locked={self.locked} archived={self.archived}>"
)
def __str__(self) -> str:
return self.name
def _from_data(self, data: ThreadPayload) -> None:
self.id = int(data["id"])
self.parent_id = int(data["parent_id"])
self.owner_id = int(data["owner_id"])
self.name = data["name"]
self._type = try_enum(ChannelType, data["type"])
self.last_message_id = get_as_snowflake(data, "last_message_id")
self.slowmode_delay = data.get("rate_limit_per_user", 0)
self.message_count = data["message_count"]
self.member_count = data["member_count"]
self._unroll_metadata(data["thread_metadata"])
self.flags: ChannelFlags = ChannelFlags._from_value(data.get("flags", 0))
try:
member = data["member"]
except KeyError:
self.me = None
else:
self.me = ThreadMember(self, member)
self.applied_tag_ids: List[int] = [int(tag_id) for tag_id in data.get("applied_tags", [])]
def _unroll_metadata(self, data: ThreadMetadata) -> None:
self.archived = data["archived"]
self.archiver_id = get_as_snowflake(data, "archiver_id")
self.auto_archive_duration = data["auto_archive_duration"]
self.archive_timestamp = parse_time(data["archive_timestamp"])
self.locked = data.get("locked", False)
self.invitable = data.get("invitable", True)
self.create_timestamp = parse_time(data.get("create_timestamp"))
def _update(self, data) -> None:
with contextlib.suppress(KeyError):
self.name = data["name"]
self.slowmode_delay = data.get("rate_limit_per_user", 0)
self.flags: ChannelFlags = ChannelFlags._from_value(data.get("flags", 0))
self.applied_tag_ids: List[int] = [int(tag_id) for tag_id in data.get("applied_tags", [])]
with contextlib.suppress(KeyError):
self._unroll_metadata(data["thread_metadata"])
def created_at(self) -> Optional[datetime]:
"""Optional[:class:`datetime.datetime`]: Returns the threads's creation time in UTC.
This is ``None`` if the thread was created before January 9th, 2021.
.. versionadded:: 2.0
"""
return self.create_timestamp
def type(self) -> ChannelType:
""":class:`ChannelType`: The channel's Discord type."""
return self._type
def parent(self) -> Optional[Union[TextChannel, ForumChannel]]:
"""Optional[Union[:class:`TextChannel`, :class:`ForumChannel`]]: The parent channel this thread belongs to."""
return self.guild.get_channel(self.parent_id) # type: ignore
def owner(self) -> Optional[Member]:
"""Optional[:class:`Member`]: The member this thread belongs to."""
return self.guild.get_member(self.owner_id)
def mention(self) -> str:
""":class:`str`: The string that allows you to mention the thread."""
return f"<#{self.id}>"
def members(self) -> List[ThreadMember]:
"""List[:class:`ThreadMember`]: A list of thread members in this thread.
This requires :attr:`Intents.members` to be properly filled. Most of the time however,
this data is not provided by the gateway and a call to :meth:`fetch_members` is
needed.
"""
return list(self._members.values())
def last_message(self) -> Optional[Message]:
"""Fetches the last message from this channel in cache.
The message might not be valid or point to an existing message.
.. admonition:: Reliable Fetching
:class: helpful
For a slightly more reliable method of fetching the
last message, consider using either :meth:`history`
or :meth:`fetch_message` with the :attr:`last_message_id`
attribute.
Returns
-------
Optional[:class:`Message`]
The last message in this channel or ``None`` if not found.
"""
return self._state._get_message(self.last_message_id) if self.last_message_id else None
def category(self) -> Optional[CategoryChannel]:
"""The category channel the parent channel belongs to, if applicable.
Raises
------
ClientException
The parent channel was not cached and returned ``None``.
Returns
-------
Optional[:class:`CategoryChannel`]
The parent channel's category.
"""
parent = self.parent
if parent is None:
raise ClientException("Parent channel not found")
return parent.category
def category_id(self) -> Optional[int]:
"""The category channel ID the parent channel belongs to, if applicable.
Raises
------
ClientException
The parent channel was not cached and returned ``None``.
Returns
-------
Optional[:class:`int`]
The parent channel's category ID.
"""
parent = self.parent
if parent is None:
raise ClientException("Parent channel not found")
return parent.category_id
def jump_url(self) -> str:
""":class:`str`: Returns a URL that allows the client to jump to this channel.
.. versionadded:: 2.0
"""
return f"https://discord.com/channels/{self.guild.id}/{self.id}"
def applied_tags(self) -> Optional[List[ForumTag]]:
"""Optional[List[:class:`ForumTag`]]: A list of tags applied to this thread.
This is ``None`` if the parent channel was not found in cache.
.. versionadded:: 2.4
"""
if self.parent is None:
return None
parent = self.parent
if not isinstance(parent, channel.ForumChannel):
return None
tags: List[ForumTag] = []
for tag_id in self.applied_tag_ids:
tag = parent.get_tag(tag_id)
if tag is not None:
tags.append(tag)
return tags
def is_private(self) -> bool:
""":class:`bool`: Whether the thread is a private thread.
A private thread is only viewable by those that have been explicitly
invited or have :attr:`~.Permissions.manage_threads`.
"""
return self._type is ChannelType.private_thread
def is_news(self) -> bool:
""":class:`bool`: Whether the thread is a news thread.
A news thread is a thread that has a parent that is a news channel,
i.e. :meth:`.TextChannel.is_news` is ``True``.
"""
return self._type is ChannelType.news_thread
def is_nsfw(self) -> bool:
""":class:`bool`: Whether the thread is NSFW or not.
An NSFW thread is a thread that has a parent that is an NSFW channel,
i.e. :meth:`.TextChannel.is_nsfw` is ``True``.
"""
parent = self.parent
return parent is not None and parent.is_nsfw()
def permissions_for(self, obj: Union[Member, Role], /) -> Permissions:
"""Handles permission resolution for the :class:`~nextcord.Member`
or :class:`~nextcord.Role`.
Since threads do not have their own permissions, they inherit them
from the parent channel. This is a convenience method for
calling :meth:`~nextcord.TextChannel.permissions_for` on the
parent channel.
Parameters
----------
obj: Union[:class:`~nextcord.Member`, :class:`~nextcord.Role`]
The object to resolve permissions for. This could be either
a member or a role. If it's a role then member overwrites
are not computed.
Raises
------
ClientException
The parent channel was not cached and returned ``None``
Returns
-------
:class:`~nextcord.Permissions`
The resolved permissions for the member or role.
"""
parent = self.parent
if parent is None:
raise ClientException("Parent channel not found")
return parent.permissions_for(obj)
async def delete_messages(self, messages: Iterable[Snowflake]) -> None:
"""|coro|
Deletes a list of messages. This is similar to :meth:`Message.delete`
except it bulk deletes multiple messages.
As a special case, if the number of messages is 0, then nothing
is done. If the number of messages is 1 then single message
delete is done. If it's more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that
are older than 14 days old.
You must have the :attr:`~Permissions.manage_messages` permission to
use this.
Usable only by bot accounts.
Parameters
----------
messages: Iterable[:class:`abc.Snowflake`]
An iterable of messages denoting which ones to bulk delete.
Raises
------
ClientException
The number of messages to delete was more than 100.
Forbidden
You do not have proper permissions to delete the messages or
you're not using a bot account.
NotFound
If single delete, then the message was already deleted.
HTTPException
Deleting the messages failed.
"""
if not isinstance(messages, (list, tuple)):
messages = list(messages)
if len(messages) == 0:
return # do nothing
if len(messages) == 1:
message_id = messages[0].id
await self._state.http.delete_message(self.id, message_id)
return
if len(messages) > 100:
raise ClientException("Can only bulk delete messages up to 100 messages")
message_ids: SnowflakeList = [m.id for m in messages]
await self._state.http.delete_messages(self.id, message_ids)
async def purge(
self,
*,
limit: Optional[int] = 100,
check: Callable[[Message], bool] = MISSING,
before: Optional[SnowflakeTime] = None,
after: Optional[SnowflakeTime] = None,
around: Optional[SnowflakeTime] = None,
oldest_first: Optional[bool] = False,
bulk: bool = True,
) -> List[Message]:
"""|coro|
Purges a list of messages that meet the criteria given by the predicate
``check``. If a ``check`` is not provided then all messages are deleted
without discrimination.
You must have the :attr:`~Permissions.manage_messages` permission to
delete messages even if they are your own (unless you are a user
account). The :attr:`~Permissions.read_message_history` permission is
also needed to retrieve message history.
Examples
--------
Deleting bot's messages ::
def is_me(m):
return m.author == client.user
deleted = await thread.purge(limit=100, check=is_me)
await thread.send(f'Deleted {len(deleted)} message(s)')
Parameters
----------
limit: Optional[:class:`int`]
The number of messages to search through. This is not the number
of messages that will be deleted, though it can be.
check: Callable[[:class:`Message`], :class:`bool`]
The function used to check if a message should be deleted.
It must take a :class:`Message` as its sole parameter.
before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]]
Same as ``before`` in :meth:`history`.
after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]]
Same as ``after`` in :meth:`history`.
around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]]
Same as ``around`` in :meth:`history`.
oldest_first: Optional[:class:`bool`]
Same as ``oldest_first`` in :meth:`history`.
bulk: :class:`bool`
If ``True``, use bulk delete. Setting this to ``False`` is useful for mass-deleting
a bot's own messages without :attr:`Permissions.manage_messages`. When ``True``, will
fall back to single delete if messages are older than two weeks.
Raises
------
Forbidden
You do not have proper permissions to do the actions required.
HTTPException
Purging the messages failed.
Returns
-------
List[:class:`.Message`]
The list of messages that were deleted.
"""
if check is MISSING:
check = lambda _: True
iterator = self.history(
limit=limit, before=before, after=after, oldest_first=oldest_first, around=around
)
ret: List[Message] = []
count = 0
minimum_time = int((time.time() - 14 * 24 * 60 * 60) * 1000.0 - 1420070400000) << 22
async def _single_delete_strategy(messages: Iterable[Message]) -> None:
for m in messages:
await m.delete()
strategy = self.delete_messages if bulk else _single_delete_strategy
async for message in iterator:
if count == 100:
to_delete = ret[-100:]
await strategy(to_delete)
count = 0
await asyncio.sleep(1)
if not check(message):
continue
if message.id < minimum_time:
# older than 14 days old
if count == 1:
await ret[-1].delete()
elif count >= 2:
to_delete = ret[-count:]
await strategy(to_delete)
count = 0
strategy = _single_delete_strategy
count += 1
ret.append(message)
# SOme messages remaining to poll
if count >= 2:
# more than 2 messages -> bulk delete
to_delete = ret[-count:]
await strategy(to_delete)
elif count == 1:
# delete a single message
await ret[-1].delete()
return ret
async def edit(
self,
*,
name: str = MISSING,
archived: bool = MISSING,
locked: bool = MISSING,
invitable: bool = MISSING,
slowmode_delay: int = MISSING,
auto_archive_duration: ThreadArchiveDuration = MISSING,
flags: ChannelFlags = MISSING,
applied_tags: List[ForumTag] = MISSING,
) -> Thread:
"""|coro|
Edits the thread.
Editing the thread requires :attr:`.Permissions.manage_threads`. The thread
creator can also edit ``name``, ``archived`` or ``auto_archive_duration``.
Note that if the thread is locked then only those with :attr:`.Permissions.manage_threads`
can unarchive a thread.
The thread must be unarchived to be edited.
Parameters
----------
name: :class:`str`
The new name of the thread.
archived: :class:`bool`
Whether to archive the thread or not.
locked: :class:`bool`
Whether to lock the thread or not.
invitable: :class:`bool`
Whether non-moderators can add other non-moderators to this thread.
Only available for private threads.
auto_archive_duration: :class:`int`
The new duration in minutes before a thread is automatically archived for inactivity.
Must be one of ``60``, ``1440``, ``4320``, or ``10080``.
slowmode_delay: :class:`int`
Specifies the slowmode rate limit for user in this thread, in seconds.
A value of ``0`` disables slowmode. The maximum value possible is ``21600``.
flags: :class:`ChannelFlags`
The new channel flags to use for this thread.
.. versionadded:: 2.1
applied_tags: List[:class:`ForumTag`]
The new tags to apply to this thread.
.. versionadded:: 2.4
Raises
------
Forbidden
You do not have permissions to edit the thread.
HTTPException
Editing the thread failed.
Returns
-------
:class:`Thread`
The newly edited thread.
"""
payload = {}
if name is not MISSING:
payload["name"] = str(name)
if archived is not MISSING:
payload["archived"] = archived
if auto_archive_duration is not MISSING:
payload["auto_archive_duration"] = auto_archive_duration
if locked is not MISSING:
payload["locked"] = locked
if invitable is not MISSING:
payload["invitable"] = invitable
if slowmode_delay is not MISSING:
payload["rate_limit_per_user"] = slowmode_delay
if flags is not MISSING:
payload["flags"] = flags.value
if applied_tags is not MISSING:
payload["applied_tags"] = [tag.id for tag in applied_tags]
data = await self._state.http.edit_channel(self.id, **payload)
# The data payload will always be a Thread payload
return Thread(data=data, state=self._state, guild=self.guild) # type: ignore
async def join(self) -> None:
"""|coro|
Joins this thread.
You must have :attr:`~Permissions.send_messages_in_threads` to join a thread.
If the thread is private, :attr:`~Permissions.manage_threads` is also needed.
Raises
------
Forbidden
You do not have permissions to join the thread.
HTTPException
Joining the thread failed.
"""
await self._state.http.join_thread(self.id)
async def leave(self) -> None:
"""|coro|
Leaves this thread.
Raises
------
HTTPException
Leaving the thread failed.
"""
await self._state.http.leave_thread(self.id)
async def add_user(self, user: Snowflake) -> None:
"""|coro|
Adds a user to this thread.
You must have :attr:`~Permissions.send_messages` and :attr:`~Permissions.use_threads`
to add a user to a public thread. If the thread is private then :attr:`~Permissions.send_messages`
and either :attr:`~Permissions.use_private_threads` or :attr:`~Permissions.manage_messages`
is required to add a user to the thread.
Parameters
----------
user: :class:`abc.Snowflake`
The user to add to the thread.
Raises
------
Forbidden
You do not have permissions to add the user to the thread.
HTTPException
Adding the user to the thread failed.
"""
await self._state.http.add_user_to_thread(self.id, user.id)
async def remove_user(self, user: Snowflake) -> None:
"""|coro|
Removes a user from this thread.
You must have :attr:`~Permissions.manage_threads` or be the creator of the thread to remove a user.
Parameters
----------
user: :class:`abc.Snowflake`
The user to add to the thread.
Raises
------
Forbidden
You do not have permissions to remove the user from the thread.
HTTPException
Removing the user from the thread failed.
"""
await self._state.http.remove_user_from_thread(self.id, user.id)
async def fetch_members(self) -> List[ThreadMember]:
"""|coro|
Retrieves all :class:`ThreadMember` that are in this thread.
This requires :attr:`Intents.members` to get information about members
other than yourself.
Raises
------
HTTPException
Retrieving the members failed.
Returns
-------
List[:class:`ThreadMember`]
All thread members in the thread.
"""
members = await self._state.http.get_thread_members(self.id)
return [ThreadMember(parent=self, data=data) for data in members]
async def delete(self) -> None:
"""|coro|
Deletes this thread.
You must have :attr:`~Permissions.manage_threads` to delete threads.
Raises
------
Forbidden
You do not have permissions to delete this thread.
HTTPException
Deleting the thread failed.
"""
await self._state.http.delete_channel(self.id)
def get_partial_message(self, message_id: int, /) -> PartialMessage:
"""Creates a :class:`PartialMessage` from the message ID.
This is useful if you want to work with a message and only have its ID without
doing an unnecessary API call.
.. versionadded:: 2.0
Parameters
----------
message_id: :class:`int`
The message ID to create a partial message for.
Returns
-------
:class:`PartialMessage`
The partial message.
"""
from .message import PartialMessage
return PartialMessage(channel=self, id=message_id)
def _add_member(self, member: ThreadMember) -> None:
self._members[member.id] = member
def _pop_member(self, member_id: int) -> Optional[ThreadMember]:
return self._members.pop(member_id, None)
def _threaded_guild_channel_factory(channel_type: int):
cls, value = _guild_channel_factory(channel_type)
if value in (ChannelType.private_thread, ChannelType.public_thread, ChannelType.news_thread):
return Thread, value
return cls, value | null |
161,018 | from __future__ import annotations
import contextlib
import json
import logging
import re
import threading
import time
from types import TracebackType
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple, Type, Union, overload
from urllib.parse import quote as urlquote
from weakref import WeakValueDictionary
from .. import utils
from ..channel import PartialMessageable
from ..errors import DiscordServerError, Forbidden, HTTPException, InvalidArgument, NotFound
from ..http import _USER_AGENT, Route
from ..message import Attachment, Message
from .async_ import BaseWebhook, _WebhookState, handle_message_parameters
class WebhookAdapter:
def __init__(self) -> None:
self._locks: WeakValueDictionary[
Tuple[Optional[SnowflakeAlias], Optional[str]],
threading.Lock,
] = WeakValueDictionary()
def request(
self,
route: Route,
session: Session,
*,
payload: Optional[Dict[str, Any]] = None,
multipart: Optional[List[Dict[str, Any]]] = None,
files: Optional[List[File]] = None,
reason: Optional[str] = None,
auth_token: Optional[str] = None,
params: Optional[Dict[str, Any]] = None,
) -> Any:
# always ensure our user agent is being used
headers: Dict[str, str] = {"User-Agent": _USER_AGENT}
files = files or []
to_send: Optional[Union[str, Dict[str, Any]]] = None
bucket = (route.webhook_id, route.webhook_token)
try:
lock = self._locks[bucket]
except KeyError:
self._locks[bucket] = lock = threading.Lock()
if payload is not None:
headers["Content-Type"] = "application/json"
to_send = utils.to_json(payload)
if auth_token is not None:
headers["Authorization"] = f"Bot {auth_token}"
if reason is not None:
headers["X-Audit-Log-Reason"] = urlquote(reason, safe="/ ")
response: Optional[Response] = None
data: Optional[Union[Dict[str, Any], str]] = None
file_data: Optional[Dict[str, Any]] = None
method = route.method
url = route.url
webhook_id = route.webhook_id
with DeferredLock(lock) as lock:
for attempt in range(5):
for file in files:
file.reset(seek=attempt)
if multipart:
file_data = {}
for p in multipart:
name = p["name"]
if name == "payload_json":
to_send = {"payload_json": p["value"]}
else:
file_data[name] = (p["filename"], p["value"], p["content_type"])
try:
with session.request(
method, url, data=to_send, files=file_data, headers=headers, params=params
) as response:
_log.debug(
"Webhook ID %s with %s %s has returned status code %s",
webhook_id,
method,
url,
response.status_code,
)
response.encoding = "utf-8"
# Compatibility with aiohttp
response.status = response.status_code # type: ignore
data = response.text or None
if data and response.headers["Content-Type"] == "application/json":
data = json.loads(data)
remaining = response.headers.get("X-Ratelimit-Remaining")
if remaining == "0" and response.status_code != 429:
delta = utils.parse_ratelimit_header(response)
_log.debug(
"Webhook ID %s has been pre-emptively rate limited, waiting %.2f seconds",
webhook_id,
delta,
)
lock.delay_by(delta)
if 300 > response.status_code >= 200:
return data
if response.status_code == 429:
if not response.headers.get("Via"):
raise HTTPException(response, data)
retry_after: float = data["retry_after"] # type: ignore
_log.warning(
"Webhook ID %s is rate limited. Retrying in %.2f seconds",
webhook_id,
retry_after,
)
time.sleep(retry_after)
continue
if response.status_code >= 500:
time.sleep(1 + attempt * 2)
continue
if response.status_code == 403:
raise Forbidden(response, data)
if response.status_code == 404:
raise NotFound(response, data)
raise HTTPException(response, data)
except OSError as e:
if attempt < 4 and e.errno in (54, 10054):
time.sleep(1 + attempt * 2)
continue
raise
if response:
if response.status_code >= 500:
raise DiscordServerError(response, data)
raise HTTPException(response, data)
raise RuntimeError("Unreachable code in HTTP handling.")
def delete_webhook(
self,
webhook_id: int,
*,
token: Optional[str] = None,
session: Session,
reason: Optional[str] = None,
):
route = Route("DELETE", "/webhooks/{webhook_id}", webhook_id=webhook_id)
return self.request(route, session, reason=reason, auth_token=token)
def delete_webhook_with_token(
self,
webhook_id: int,
token: str,
*,
session: Session,
reason: Optional[str] = None,
):
route = Route(
"DELETE",
"/webhooks/{webhook_id}/{webhook_token}",
webhook_id=webhook_id,
webhook_token=token,
)
return self.request(route, session, reason=reason)
def edit_webhook(
self,
webhook_id: int,
token: str,
payload: Dict[str, Any],
*,
session: Session,
reason: Optional[str] = None,
):
route = Route("PATCH", "/webhooks/{webhook_id}", webhook_id=webhook_id)
return self.request(route, session, reason=reason, payload=payload, auth_token=token)
def edit_webhook_with_token(
self,
webhook_id: int,
token: str,
payload: Dict[str, Any],
*,
session: Session,
reason: Optional[str] = None,
):
route = Route(
"PATCH",
"/webhooks/{webhook_id}/{webhook_token}",
webhook_id=webhook_id,
webhook_token=token,
)
return self.request(route, session, reason=reason, payload=payload)
def execute_webhook(
self,
webhook_id: int,
token: str,
*,
session: Session,
payload: Optional[Dict[str, Any]] = None,
multipart: Optional[List[Dict[str, Any]]] = None,
files: Optional[List[File]] = None,
thread_id: Optional[int] = None,
wait: bool = False,
):
params = {"wait": int(wait)}
if thread_id:
params["thread_id"] = thread_id
route = Route(
"POST",
"/webhooks/{webhook_id}/{webhook_token}",
webhook_id=webhook_id,
webhook_token=token,
)
return self.request(
route, session, payload=payload, multipart=multipart, files=files, params=params
)
def get_webhook_message(
self,
webhook_id: int,
token: str,
message_id: int,
*,
session: Session,
):
route = Route(
"GET",
"/webhooks/{webhook_id}/{webhook_token}/messages/{message_id}",
webhook_id=webhook_id,
webhook_token=token,
message_id=message_id,
)
return self.request(route, session)
def edit_webhook_message(
self,
webhook_id: int,
token: str,
message_id: int,
*,
session: Session,
payload: Optional[Dict[str, Any]] = None,
multipart: Optional[List[Dict[str, Any]]] = None,
files: Optional[List[File]] = None,
):
route = Route(
"PATCH",
"/webhooks/{webhook_id}/{webhook_token}/messages/{message_id}",
webhook_id=webhook_id,
webhook_token=token,
message_id=message_id,
)
return self.request(route, session, payload=payload, multipart=multipart, files=files)
def delete_webhook_message(
self,
webhook_id: int,
token: str,
message_id: int,
*,
session: Session,
):
route = Route(
"DELETE",
"/webhooks/{webhook_id}/{webhook_token}/messages/{message_id}",
webhook_id=webhook_id,
webhook_token=token,
message_id=message_id,
)
return self.request(route, session)
def fetch_webhook(
self,
webhook_id: int,
token: str,
*,
session: Session,
):
route = Route("GET", "/webhooks/{webhook_id}", webhook_id=webhook_id)
return self.request(route, session=session, auth_token=token)
def fetch_webhook_with_token(
self,
webhook_id: int,
token: str,
*,
session: Session,
):
route = Route(
"GET",
"/webhooks/{webhook_id}/{webhook_token}",
webhook_id=webhook_id,
webhook_token=token,
)
return self.request(route, session=session)
_context = _WebhookContext()
def _get_webhook_adapter() -> WebhookAdapter:
if _context.adapter is None:
_context.adapter = WebhookAdapter()
return _context.adapter | null |
161,019 | from __future__ import annotations
import asyncio
import contextlib
import json
import logging
import re
from contextvars import ContextVar
from types import TracebackType
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Literal,
NamedTuple,
Optional,
Tuple,
Type,
Union,
overload,
)
from urllib.parse import quote as urlquote
from weakref import WeakValueDictionary
import aiohttp
from .. import utils
from ..asset import Asset
from ..channel import PartialMessageable
from ..enums import WebhookType, try_enum
from ..errors import DiscordServerError, Forbidden, HTTPException, InvalidArgument, NotFound
from ..flags import MessageFlags
from ..http import _USER_AGENT, Route
from ..message import Attachment, Message
from ..mixins import Hashable
from ..user import BaseUser, User
MISSING = utils.MISSING
class ExecuteWebhookParameters(NamedTuple):
class InvalidArgument(ClientException):
class MessageFlags(BaseFlags):
def crossposted(self) -> int:
def is_crossposted(self) -> int:
def suppress_embeds(self) -> int:
def source_message_deleted(self) -> int:
def urgent(self) -> int:
def has_thread(self) -> int:
def ephemeral(self) -> int:
def loading(self) -> int:
def failed_to_mention_roles(self) -> int:
def suppress_notifications(self) -> int:
class Attachment(Hashable):
def __init__(self, *, data: AttachmentPayload, state: ConnectionState) -> None:
def is_spoiler(self) -> bool:
def __repr__(self) -> str:
def __str__(self) -> str:
async def save(
self,
fp: Union[io.BufferedIOBase, PathLike, str],
*,
seek_begin: bool = True,
use_cached: bool = False,
) -> int:
async def read(self, *, use_cached: bool = False) -> bytes:
async def to_file(
self,
*,
filename: Optional[str] = MISSING,
description: Optional[str] = MISSING,
use_cached: bool = False,
spoiler: bool = False,
force_close: bool = True,
) -> File:
def to_dict(self) -> AttachmentPayload:
def flags(self) -> AttachmentFlags:
def is_remix(self) -> bool:
class Embed:
def __init__(
self,
*,
colour: Optional[Union[int, Colour]] = None,
color: Optional[Union[int, Colour]] = None,
title: Optional[Any] = None,
type: EmbedType = "rich",
url: Optional[Any] = None,
description: Optional[Any] = None,
timestamp: Optional[datetime.datetime] = None,
) -> None:
def Empty(self) -> None:
def from_dict(cls, data: Mapping[str, Any]) -> Self:
def copy(self) -> Self:
def __len__(self) -> int:
def __bool__(self) -> bool:
def colour(self) -> Optional[Colour]:
def colour(self, value: Optional[Union[int, Colour]]):
def timestamp(self) -> Optional[datetime.datetime]:
def timestamp(self, value: Optional[datetime.datetime]):
def footer(self) -> _EmbedFooterProxy:
def set_footer(self, *, text: Optional[Any] = None, icon_url: Optional[Any] = None) -> Self:
def remove_footer(self) -> Self:
def image(self) -> _EmbedMediaProxy:
def set_image(self, url: Optional[Any]) -> Self:
def thumbnail(self) -> _EmbedMediaProxy:
def set_thumbnail(self, url: Optional[Any]) -> Self:
def video(self) -> _EmbedVideoProxy:
def provider(self) -> _EmbedProviderProxy:
def author(self) -> _EmbedAuthorProxy:
def set_author(
self,
*,
name: Any,
url: Optional[Any] = None,
icon_url: Optional[Any] = None,
) -> Self:
def remove_author(self) -> Self:
def fields(self) -> List[_EmbedFieldProxy]:
def add_field(self, *, name: Any, value: Any, inline: bool = True) -> Self:
def insert_field_at(self, index: int, *, name: Any, value: Any, inline: bool = True) -> Self:
def clear_fields(self) -> Self:
def remove_field(self, index: int) -> Self:
def set_field_at(self, index: int, *, name: Any, value: Any, inline: bool = True) -> Self:
def to_dict(self) -> EmbedData: # type: ignore
class File:
def __init__(
self,
fp: Union[str, bytes, os.PathLike, io.BufferedIOBase],
filename: Optional[str] = None,
*,
description: Optional[str] = None,
spoiler: bool = False,
force_close: Optional[bool] = None,
) -> None:
def __enter__(self) -> File:
def __exit__(self, *_) -> None:
def reset(self, *, seek: Union[int, bool] = True) -> None:
def close(self) -> None:
class AllowedMentions:
def __init__(
self,
*,
everyone: Optional[bool] = None,
users: Optional[Union[bool, List[Snowflake]]] = None,
roles: Optional[Union[bool, List[Snowflake]]] = None,
replied_user: Optional[bool] = None,
) -> None:
def all(cls) -> Self:
def none(cls) -> Self:
def to_dict(self) -> AllowedMentionsPayload:
def merge(self, other: AllowedMentions) -> AllowedMentions:
def __repr__(self) -> str:
class View:
def __init_subclass__(cls) -> None:
def __init__(
self,
*,
timeout: Optional[float] = 180.0,
auto_defer: bool = True,
prevent_update: bool = True,
) -> None:
def __repr__(self) -> str:
async def __timeout_task_impl(self) -> None:
def to_components(self) -> List[ActionRowPayload]:
def key(item: Item) -> int:
def from_message(cls, message: Message, /, *, timeout: Optional[float] = 180.0) -> View:
def _expires_at(self) -> Optional[float]:
def add_item(self, item: Item[Self]) -> None:
def remove_item(self, item: Item) -> None:
def clear_items(self) -> None:
async def interaction_check(self, interaction: Interaction) -> bool:
async def on_timeout(self) -> None:
async def on_error(self, error: Exception, item: Item, interaction: Interaction) -> None:
async def _scheduled_task(self, item: Item, interaction: Interaction):
def _start_listening_from_store(self, store: ViewStore) -> None:
def _dispatch_timeout(self) -> None:
def _dispatch_item(self, item: Item, interaction: Interaction) -> None:
def refresh(self, components: List[Component]) -> None:
def stop(self) -> None:
def is_finished(self) -> bool:
def is_dispatching(self) -> bool:
def is_persistent(self) -> bool:
async def wait(self) -> bool:
def handle_message_parameters(
content: Optional[str] = MISSING,
*,
username: str = MISSING,
avatar_url: Any = MISSING,
tts: bool = False,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
embed: Optional[Embed] = MISSING,
embeds: List[Embed] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = MISSING,
previous_allowed_mentions: Optional[AllowedMentions] = None,
ephemeral: Optional[bool] = None,
flags: Optional[MessageFlags] = None,
suppress_embeds: Optional[bool] = None,
) -> ExecuteWebhookParameters:
if files is not MISSING and file is not MISSING:
raise InvalidArgument("Cannot mix file and files keyword arguments.")
if embeds is not MISSING and embed is not MISSING:
raise InvalidArgument("Cannot mix embed and embeds keyword arguments.")
payload: Dict[str, Any] | None = {}
if file is not MISSING or files is not MISSING:
payload["attachments"] = []
if attachments is not MISSING:
payload["attachments"] = [a.to_dict() for a in attachments]
if embeds is not MISSING:
payload["embeds"] = [e.to_dict() for e in embeds]
if embed is not MISSING:
if embed is None:
payload["embeds"] = []
else:
payload["embeds"] = [embed.to_dict()]
if content is not MISSING:
if content is not None:
payload["content"] = str(content)
else:
payload["content"] = None
if view is not MISSING:
if view is not None:
payload["components"] = view.to_components()
else:
payload["components"] = []
payload["tts"] = tts
if avatar_url:
payload["avatar_url"] = str(avatar_url)
if username:
payload["username"] = username
if flags is None:
flags = MessageFlags()
if suppress_embeds is not None:
flags.suppress_embeds = suppress_embeds
if ephemeral is not None:
flags.ephemeral = ephemeral
if flags.value != 0:
payload["flags"] = flags.value
if allowed_mentions:
if previous_allowed_mentions is not None:
payload["allowed_mentions"] = previous_allowed_mentions.merge(
allowed_mentions
).to_dict()
else:
payload["allowed_mentions"] = allowed_mentions.to_dict()
elif previous_allowed_mentions is not None:
payload["allowed_mentions"] = previous_allowed_mentions.to_dict()
multipart = []
if file is not MISSING:
files = [file]
if files:
multipart.append({"name": "payload_json"})
for index, file in enumerate(files):
payload["attachments"].append(
{
"id": index,
"filename": file.filename,
"description": file.description, # type: ignore
# ignore complaints about assigning to an Attachment
}
)
multipart.append(
{
"name": f"files[{index}]",
"value": file.fp,
"filename": file.filename,
"content_type": "application/octet-stream",
}
)
multipart[0]["value"] = utils.to_json(payload)
payload = None
return ExecuteWebhookParameters(payload=payload, multipart=multipart, files=files) | null |
161,020 | from __future__ import annotations
import asyncio
import contextlib
import copy
import inspect
import itertools
import logging
import os
import warnings
from collections import OrderedDict, deque
from typing import (
TYPE_CHECKING,
Any,
Callable,
Coroutine,
Deque,
Dict,
List,
Optional,
Set,
Tuple,
TypeVar,
Union,
)
from . import utils
from .activity import BaseActivity
from .application_command import BaseApplicationCommand
from .audit_logs import AuditLogEntry
from .auto_moderation import AutoModerationActionExecution, AutoModerationRule
from .channel import *
from .channel import _channel_factory
from .emoji import Emoji
from .enums import ChannelType, Status, try_enum
from .errors import Forbidden
from .flags import ApplicationFlags, Intents, MemberCacheFlags
from .guild import Guild
from .integrations import _integration_factory
from .invite import Invite
from .member import Member
from .mentions import AllowedMentions
from .message import Message
from .object import Object
from .partial_emoji import PartialEmoji
from .raw_models import *
from .role import Role
from .scheduled_events import ScheduledEvent, ScheduledEventUser
from .stage_instance import StageInstance
from .sticker import GuildSticker
from .threads import Thread, ThreadMember
from .ui.modal import Modal, ModalStore
from .ui.view import View, ViewStore
from .user import ClientUser, User
_log = logging.getLogger(__name__)
async def logging_coroutine(coroutine: Coroutine[Any, Any, T], *, info: str) -> Optional[T]:
try:
await coroutine
except Exception:
_log.exception("Exception occurred during %s", info) | null |
161,021 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import io
import re
from os import PathLike
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
List,
Optional,
Set,
Tuple,
Union,
overload,
)
from . import utils
from .components import _component_factory
from .embeds import Embed
from .emoji import Emoji
from .enums import ChannelType, MessageType, try_enum
from .errors import HTTPException, InvalidArgument
from .file import File
from .flags import AttachmentFlags, MessageFlags
from .guild import Guild
from .member import Member
from .mixins import Hashable
from .partial_emoji import PartialEmoji
from .reaction import Reaction
from .sticker import StickerItem
from .threads import Thread
from .utils import MISSING, escape_mentions
class Emoji(_EmojiTag, AssetMixin):
def __init__(
self, *, guild: Union[Guild, GuildPreview], state: ConnectionState, data: EmojiPayload
) -> None:
def _from_data(self, emoji: EmojiPayload) -> None:
def _to_partial(self) -> PartialEmoji:
def __iter__(self) -> Iterator[Tuple[str, Any]]:
def __str__(self) -> str:
def __repr__(self) -> str:
def __eq__(self, other: Any) -> bool:
def __ne__(self, other: Any) -> bool:
def __hash__(self) -> int:
def created_at(self) -> datetime:
def url(self) -> str:
def roles(self) -> List[Role]:
def guild(self) -> Guild:
def is_usable(self) -> bool:
async def delete(self, *, reason: Optional[str] = None) -> None:
async def edit(
self, *, name: str = MISSING, roles: List[Snowflake] = MISSING, reason: Optional[str] = None
) -> Emoji:
class InvalidArgument(ClientException):
class PartialEmoji(_EmojiTag, AssetMixin):
def __init__(self, *, name: str, animated: bool = False, id: Optional[int] = None) -> None:
def from_dict(cls, data: Union[PartialEmojiPayload, Dict[str, Any]]) -> Self:
def from_default_reaction(cls, data: DefaultReaction) -> Self:
def from_str(cls, value: str) -> Self:
def to_dict(self) -> Dict[str, Any]:
def _to_partial(self) -> PartialEmoji:
def with_state(
cls,
state: ConnectionState,
*,
name: str,
animated: bool = False,
id: Optional[int] = None,
) -> Self:
def __str__(self) -> str:
def __repr__(self) -> str:
def __eq__(self, other: Any) -> bool:
def __ne__(self, other: Any) -> bool:
def __hash__(self) -> int:
def is_custom_emoji(self) -> bool:
def is_unicode_emoji(self) -> bool:
def _as_reaction(self) -> str:
def created_at(self) -> Optional[datetime]:
def url(self) -> str:
async def read(self) -> bytes:
class Reaction:
def __init__(
self,
*,
message: Message,
data: ReactionPayload,
emoji: Optional[Union[PartialEmoji, Emoji, str]] = None,
) -> None:
def is_custom_emoji(self) -> bool:
def __eq__(self, other: Any) -> bool:
def __ne__(self, other: Any) -> bool:
def __hash__(self) -> int:
def __str__(self) -> str:
def __repr__(self) -> str:
async def remove(self, user: Snowflake) -> None:
async def clear(self) -> None:
def users(
self, *, limit: Optional[int] = None, after: Optional[Snowflake] = None
) -> ReactionIterator:
def convert_emoji_reaction(emoji):
if isinstance(emoji, Reaction):
emoji = emoji.emoji
if isinstance(emoji, Emoji):
return f"{emoji.name}:{emoji.id}"
if isinstance(emoji, PartialEmoji):
return emoji._as_reaction()
if isinstance(emoji, str):
# Reactions can be in :name:id format, but not <:name:id>.
# No existing emojis have <> in them, so this should be okay.
return emoji.strip("<>")
raise InvalidArgument(
f"emoji argument must be str, Emoji, or Reaction not {emoji.__class__.__name__}."
) | null |
161,022 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import io
import re
from os import PathLike
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
List,
Optional,
Set,
Tuple,
Union,
overload,
)
from . import utils
from .components import _component_factory
from .embeds import Embed
from .emoji import Emoji
from .enums import ChannelType, MessageType, try_enum
from .errors import HTTPException, InvalidArgument
from .file import File
from .flags import AttachmentFlags, MessageFlags
from .guild import Guild
from .member import Member
from .mixins import Hashable
from .partial_emoji import PartialEmoji
from .reaction import Reaction
from .sticker import StickerItem
from .threads import Thread
from .utils import MISSING, escape_mentions
def flatten_handlers(cls):
prefix = len("_handle_")
handlers = [
(key[prefix:], value)
for key, value in cls.__dict__.items()
if key.startswith("_handle_") and key != "_handle_member"
]
# store _handle_member last
handlers.append(("member", cls._handle_member))
cls._HANDLERS = handlers
cls._CACHED_SLOTS = [attr for attr in cls.__slots__ if attr.startswith("_cs_")]
return cls | null |
161,023 | from __future__ import annotations
import array
import ctypes
import ctypes.util
import logging
import math
import os.path
import struct
import sys
from typing import (
TYPE_CHECKING,
Any,
Callable,
List,
Literal,
Optional,
Tuple,
TypedDict,
TypeVar,
overload,
)
from .errors import DiscordException, InvalidArgument
_log = logging.getLogger(__name__)
OK = 0
class OpusError(DiscordException):
"""An exception that is thrown for libopus related errors.
Attributes
----------
code: :class:`int`
The error code returned.
"""
def __init__(self, code: int) -> None:
self.code: int = code
msg = _lib.opus_strerror(self.code).decode("utf-8")
_log.info('"%s" has happened', msg)
super().__init__(msg)
def _err_lt(result: int, func: Callable, _args: List) -> int:
if result < OK:
_log.info("error has happened in %s", func.__name__)
raise OpusError(result)
return result | null |
161,024 | from __future__ import annotations
import array
import ctypes
import ctypes.util
import logging
import math
import os.path
import struct
import sys
from typing import (
TYPE_CHECKING,
Any,
Callable,
List,
Literal,
Optional,
Tuple,
TypedDict,
TypeVar,
overload,
)
from .errors import DiscordException, InvalidArgument
_log = logging.getLogger(__name__)
OK = 0
class OpusError(DiscordException):
"""An exception that is thrown for libopus related errors.
Attributes
----------
code: :class:`int`
The error code returned.
"""
def __init__(self, code: int) -> None:
self.code: int = code
msg = _lib.opus_strerror(self.code).decode("utf-8")
_log.info('"%s" has happened', msg)
super().__init__(msg)
def _err_ne(result: T, func: Callable, args: List) -> T:
ret = args[-1]._obj
if ret.value != OK:
_log.info("error has happened in %s", func.__name__)
raise OpusError(ret.value)
return result | null |
161,025 | from __future__ import annotations
import array
import ctypes
import ctypes.util
import logging
import math
import os.path
import struct
import sys
from typing import (
TYPE_CHECKING,
Any,
Callable,
List,
Literal,
Optional,
Tuple,
TypedDict,
TypeVar,
overload,
)
from .errors import DiscordException, InvalidArgument
_lib: Any = None
def libopus_loader(name: str) -> Any:
def _load_default() -> bool:
global _lib
try:
if sys.platform == "win32":
_basedir = os.path.dirname(os.path.abspath(__file__))
_bitness = struct.calcsize("P") * 8
_target = "x64" if _bitness > 32 else "x86"
_filename = os.path.join(_basedir, "bin", f"libopus-0.{_target}.dll")
_lib = libopus_loader(_filename)
else:
opus = ctypes.util.find_library("opus")
_lib = None if opus is None else libopus_loader(opus)
except Exception:
_lib = None
return _lib is not None | null |
161,026 | from __future__ import annotations
import array
import ctypes
import ctypes.util
import logging
import math
import os.path
import struct
import sys
from typing import (
TYPE_CHECKING,
Any,
Callable,
List,
Literal,
Optional,
Tuple,
TypedDict,
TypeVar,
overload,
)
from .errors import DiscordException, InvalidArgument
_lib: Any = None
def libopus_loader(name: str) -> Any:
# create the library...
lib = ctypes.cdll.LoadLibrary(name)
# register the functions...
for item in exported_functions:
func = getattr(lib, item[0])
try:
if item[1]:
func.argtypes = item[1]
func.restype = item[2]
except KeyError:
pass
try:
if item[3]:
func.errcheck = item[3]
except KeyError:
_log.exception("Error assigning check function to %s", func)
return lib
The provided code snippet includes necessary dependencies for implementing the `load_opus` function. Write a Python function `def load_opus(name: str) -> None` to solve the following problem:
Loads the libopus shared library for use with voice. If this function is not called then the library uses the function :func:`ctypes.util.find_library` and then loads that one if available. Not loading a library and attempting to use PCM based AudioSources will lead to voice not working. This function propagates the exceptions thrown. .. warning:: The bitness of the library must match the bitness of your python interpreter. If the library is 64-bit then your python interpreter must be 64-bit as well. Usually if there's a mismatch in bitness then the load will throw an exception. .. note:: On Windows, this function should not need to be called as the binaries are automatically loaded. .. note:: On Windows, the .dll extension is not necessary. However, on Linux the full extension is required to load the library, e.g. ``libopus.so.1``. On Linux however, :func:`ctypes.util.find_library` will usually find the library automatically without you having to call this. Parameters ---------- name: :class:`str` The filename of the shared library.
Here is the function:
def load_opus(name: str) -> None:
"""Loads the libopus shared library for use with voice.
If this function is not called then the library uses the function
:func:`ctypes.util.find_library` and then loads that one if available.
Not loading a library and attempting to use PCM based AudioSources will
lead to voice not working.
This function propagates the exceptions thrown.
.. warning::
The bitness of the library must match the bitness of your python
interpreter. If the library is 64-bit then your python interpreter
must be 64-bit as well. Usually if there's a mismatch in bitness then
the load will throw an exception.
.. note::
On Windows, this function should not need to be called as the binaries
are automatically loaded.
.. note::
On Windows, the .dll extension is not necessary. However, on Linux
the full extension is required to load the library, e.g. ``libopus.so.1``.
On Linux however, :func:`ctypes.util.find_library` will usually find the library automatically
without you having to call this.
Parameters
----------
name: :class:`str`
The filename of the shared library.
"""
global _lib
_lib = libopus_loader(name) | Loads the libopus shared library for use with voice. If this function is not called then the library uses the function :func:`ctypes.util.find_library` and then loads that one if available. Not loading a library and attempting to use PCM based AudioSources will lead to voice not working. This function propagates the exceptions thrown. .. warning:: The bitness of the library must match the bitness of your python interpreter. If the library is 64-bit then your python interpreter must be 64-bit as well. Usually if there's a mismatch in bitness then the load will throw an exception. .. note:: On Windows, this function should not need to be called as the binaries are automatically loaded. .. note:: On Windows, the .dll extension is not necessary. However, on Linux the full extension is required to load the library, e.g. ``libopus.so.1``. On Linux however, :func:`ctypes.util.find_library` will usually find the library automatically without you having to call this. Parameters ---------- name: :class:`str` The filename of the shared library. |
161,027 | from __future__ import annotations
import array
import ctypes
import ctypes.util
import logging
import math
import os.path
import struct
import sys
from typing import (
TYPE_CHECKING,
Any,
Callable,
List,
Literal,
Optional,
Tuple,
TypedDict,
TypeVar,
overload,
)
from .errors import DiscordException, InvalidArgument
_lib: Any = None
The provided code snippet includes necessary dependencies for implementing the `is_loaded` function. Write a Python function `def is_loaded() -> bool` to solve the following problem:
Function to check if opus lib is successfully loaded either via the :func:`ctypes.util.find_library` call of :func:`load_opus`. This must return ``True`` for voice to work. Returns ------- :class:`bool` Indicates if the opus library has been loaded.
Here is the function:
def is_loaded() -> bool:
"""Function to check if opus lib is successfully loaded either
via the :func:`ctypes.util.find_library` call of :func:`load_opus`.
This must return ``True`` for voice to work.
Returns
-------
:class:`bool`
Indicates if the opus library has been loaded.
"""
return _lib is not None | Function to check if opus lib is successfully loaded either via the :func:`ctypes.util.find_library` call of :func:`load_opus`. This must return ``True`` for voice to work. Returns ------- :class:`bool` Indicates if the opus library has been loaded. |
161,028 | import logging
from sphinx.application import Sphinx
from sphinx.util import logging as sphinx_logging
class NitpickFileIgnorer(logging.Filter):
def __init__(self, app: Sphinx) -> None:
self.app = app
super().__init__()
def filter(self, record: sphinx_logging.SphinxLogRecord) -> bool:
if getattr(record, "type", None) == "ref":
return record.location.get("refdoc") not in self.app.config.nitpick_ignore_files
return True
def setup(app: Sphinx):
app.add_config_value("nitpick_ignore_files", [], "")
f = NitpickFileIgnorer(app)
sphinx_logging.getLogger("sphinx.transforms.post_transforms").logger.addFilter(f) | null |
161,029 | from typing import Any, ClassVar, Dict
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from docutils.parsers.rst.roles import set_classes
class details(nodes.General, nodes.Element):
pass
class summary(nodes.General, nodes.Element):
pass
def visit_details_node(self, node):
self.body.append(self.starttag(node, "details", CLASS=node.attributes.get("class", "")))
def visit_summary_node(self, node):
self.body.append(self.starttag(node, "summary", CLASS=node.attributes.get("summary-class", "")))
self.body.append(node.rawsource)
def depart_details_node(self, _node):
self.body.append("</details>\n")
def depart_summary_node(self, _node):
self.body.append("</summary>")
class DetailsDirective(Directive):
final_argument_whitespace = True
optional_arguments = 1
option_spec: ClassVar[Dict[str, Any]] = {
"class": directives.class_option,
"summary-class": directives.class_option,
}
has_content = True
def run(self):
set_classes(self.options)
self.assert_has_content()
text = "\n".join(self.content)
node = details(text, **self.options)
if self.arguments:
summary_node = summary(self.arguments[0], **self.options)
summary_node.source, summary_node.line = self.state_machine.get_source_and_line(
self.lineno
)
node += summary_node
self.state.nested_parse(self.content, self.content_offset, node)
return [node]
def setup(app):
app.add_node(details, html=(visit_details_node, depart_details_node))
app.add_node(summary, html=(visit_summary_node, depart_summary_node))
app.add_directive("details", DetailsDirective) | null |
161,030 | from typing import Any, Dict, List, Optional, Tuple
import sphinx
from docutils import nodes, utils
from docutils.nodes import Node, system_message
from docutils.parsers.rst.states import Inliner
from sphinx.application import Sphinx
from sphinx.util.nodes import split_explicit_title
from sphinx.util.typing import RoleFunction
def add_link_role(app: Sphinx) -> None:
app.add_role("resource", make_link_role(app.config.resource_links))
def setup(app: Sphinx) -> Dict[str, Any]:
app.add_config_value("resource_links", {}, "env")
app.connect("builder-inited", add_link_role)
return {"version": sphinx.__display_version__, "parallel_read_safe": True} | null |
161,031 | from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.environment.adapters.indexentries import IndexEntries
from sphinx.writers.html5 import HTML5Translator
def add_custom_jinja2(app):
env = app.builder.templates.environment
env.tests["prefixedwith"] = str.startswith
env.tests["suffixedwith"] = str.endswith
def add_builders(app):
"""This is necessary because RTD injects their own for some reason."""
app.set_translator("html", DPYHTML5Translator, override=True)
app.add_builder(DPYStandaloneHTMLBuilder, override=True)
try:
original = app.registry.builders["readthedocs"]
except KeyError:
pass
else:
injected_mro = tuple(
base if base is not StandaloneHTMLBuilder else DPYStandaloneHTMLBuilder
for base in original.mro()[1:]
)
new_builder = type(original.__name__, injected_mro, {"name": "readthedocs"})
app.set_translator("readthedocs", DPYHTML5Translator, override=True)
app.add_builder(new_builder, override=True)
def setup(app):
add_builders(app)
app.connect("builder-inited", add_custom_jinja2) | null |
161,032 | from docutils import nodes
from docutils.parsers.rst import Directive
class exception_hierarchy(nodes.General, nodes.Element):
pass
def visit_exception_hierarchy_node(self, node):
self.body.append(self.starttag(node, "div", CLASS="exception-hierarchy-content"))
def depart_exception_hierarchy_node(self, _node):
self.body.append("</div>\n")
class ExceptionHierarchyDirective(Directive):
has_content = True
def run(self):
self.assert_has_content()
node = exception_hierarchy("\n".join(self.content))
self.state.nested_parse(self.content, self.content_offset, node)
return [node]
def setup(app):
app.add_node(
exception_hierarchy, html=(visit_exception_hierarchy_node, depart_exception_hierarchy_node)
)
app.add_directive("exception_hierarchy", ExceptionHierarchyDirective) | null |
161,033 | import asyncio
import importlib
import inspect
import re
from collections import OrderedDict
from typing import Callable, NamedTuple, Optional
from docutils import nodes
from sphinx import addnodes
from sphinx.locale import _
from sphinx.util.docutils import SphinxDirective
class attributetable(nodes.General, nodes.Element):
pass
class attributetablecolumn(nodes.General, nodes.Element):
pass
class attributetabletitle(nodes.TextElement):
pass
class attributetableplaceholder(nodes.General, nodes.Element):
pass
class attributetablebadge(nodes.TextElement):
pass
class attributetable_item(nodes.Part, nodes.Element):
pass
def visit_attributetable_node(self, node):
class_ = node["python-class"]
self.body.append(f'<div class="py-attribute-table" data-move-to-id="{class_}">')
def visit_attributetablecolumn_node(self, node):
self.body.append(self.starttag(node, "div", CLASS="py-attribute-table-column"))
def visit_attributetabletitle_node(self, node):
self.body.append(self.starttag(node, "span"))
def visit_attributetablebadge_node(self, node):
attributes = {
"class": "py-attribute-table-badge",
"title": node["badge-type"],
}
self.body.append(self.starttag(node, "span", **attributes))
def visit_attributetable_item_node(self, node):
self.body.append(self.starttag(node, "li", CLASS="py-attribute-table-entry"))
def depart_attributetable_node(self, _node):
self.body.append("</div>")
def depart_attributetablecolumn_node(self, _node):
self.body.append("</div>")
def depart_attributetabletitle_node(self, _node):
self.body.append("</span>")
def depart_attributetablebadge_node(self, _node):
self.body.append("</span>")
def depart_attributetable_item_node(self, _node):
self.body.append("</li>")
class PyAttributeTable(SphinxDirective):
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = False
def parse_name(self, content):
match = _name_parser_regex.match(content)
if match is None:
raise RuntimeError("could not find module name somehow")
path, name = match.groups()
if path:
modulename = path.rstrip(".")
else:
modulename = self.env.temp_data.get("autodoc:module")
if not modulename:
modulename = self.env.ref_context.get("py:module")
if modulename is None:
raise RuntimeError(
"modulename somehow None for %s in %s." % (content, self.env.docname)
)
return modulename, name
def run(self):
"""If you're curious on the HTML this is meant to generate:
<div class="py-attribute-table">
<div class="py-attribute-table-column">
<span>_('Attributes')</span>
<ul>
<li>
<a href="...">
</li>
</ul>
</div>
<div class="py-attribute-table-column">
<span>_('Methods')</span>
<ul>
<li>
<a href="..."></a>
<span class="py-attribute-badge" title="decorator">D</span>
</li>
</ul>
</div>
</div>
However, since this requires the tree to be complete
and parsed, it'll need to be done at a different stage and then
replaced.
"""
content = self.arguments[0].strip()
node = attributetableplaceholder("")
modulename, name = self.parse_name(content)
node["python-doc"] = self.env.docname
node["python-module"] = modulename
node["python-class"] = name
node["python-full-name"] = f"{modulename}.{name}"
return [node]
def process_attributetable(app, doctree, _fromdocname):
env = app.builder.env
lookup = build_lookup_table(env)
for node in doctree.traverse(attributetableplaceholder):
modulename, classname, fullname = (
node["python-module"],
node["python-class"],
node["python-full-name"],
)
groups = get_class_results(lookup, modulename, classname, fullname)
table = attributetable("")
for label, subitems in groups.items():
if not subitems:
continue
key: Callable[[TableElement], str] = lambda c: c.label
table.append(class_results_to_node(label, sorted(subitems, key=key)))
table["python-class"] = fullname
if not table:
node.replace_self([])
else:
node.replace_self([table])
def setup(app):
app.add_directive("attributetable", PyAttributeTable)
app.add_node(attributetable, html=(visit_attributetable_node, depart_attributetable_node))
app.add_node(
attributetablecolumn,
html=(visit_attributetablecolumn_node, depart_attributetablecolumn_node),
)
app.add_node(
attributetabletitle, html=(visit_attributetabletitle_node, depart_attributetabletitle_node)
)
app.add_node(
attributetablebadge, html=(visit_attributetablebadge_node, depart_attributetablebadge_node)
)
app.add_node(
attributetable_item, html=(visit_attributetable_item_node, depart_attributetable_item_node)
)
app.add_node(attributetableplaceholder)
app.connect("doctree-resolved", process_attributetable) | null |
161,034 | import os
import re
import sys
intersphinx_mapping = {
"py": ("https://docs.python.org/3", None),
"aio": ("https://docs.aiohttp.org/en/stable/", None),
"req": ("https://requests.readthedocs.io/en/latest/", None),
}
language = "en"
html_context = {
"discord_invite": "https://discord.gg/ZebatWssCB",
"discord_extensions": [
("nextcord.ext.commands", "ext/commands"),
("nextcord.ext.tasks", "ext/tasks"),
("nextcord.ext.application_checks", "ext/application_checks"),
],
}
resource_links = {
"discord": "https://discord.gg/ZebatWssCB",
"issues": "https://github.com/nextcord/nextcord/issues",
"discussions": "https://github.com/nextcord/nextcord/discussions",
"examples": f"https://github.com/nextcord/nextcord/tree/{branch}/examples",
}
def setup(app):
if app.config.language == "ja":
app.config.intersphinx_mapping["py"] = ("https://docs.python.org/ja/3", None)
app.config.html_context["discord_invite"] = "https://discord.gg/ZebatWssCB"
app.config.resource_links["discord"] = "https://discord.gg/ZebatWssCB" | null |
161,035 | import nextcord
from nextcord.ext import commands
class EphemeralCounter(nextcord.ui.View):
# When this button is pressed, it will respond with a Counter view that will
# give the button presser their own personal button they can press 5 times.
async def receive(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
# ephemeral=True makes the message hidden from everyone except the button presser
await interaction.response.send_message("Enjoy!", view=Counter(), ephemeral=True)
The provided code snippet includes necessary dependencies for implementing the `counter` function. Write a Python function `async def counter(interaction)` to solve the following problem:
Starts a counter for pressing.
Here is the function:
async def counter(interaction):
"""Starts a counter for pressing."""
await interaction.send("Press!", view=EphemeralCounter()) | Starts a counter for pressing. |
161,036 | import nextcord
from nextcord.ext import commands
class Counter(nextcord.ui.View):
# Define the actual button
# When pressed, this increments the number displayed until it hits 5.
# When it hits 5, the counter button is disabled and it turns green.
# note: The name of the function does not matter to the library
async def count(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
number = int(button.label) if button.label else 0
if number >= 4:
button.style = nextcord.ButtonStyle.green
button.disabled = True
button.label = str(number + 1)
# Make sure to update the message with our updated selves
await interaction.response.edit_message(view=self)
The provided code snippet includes necessary dependencies for implementing the `counter` function. Write a Python function `async def counter(interaction)` to solve the following problem:
Starts a counter for pressing.
Here is the function:
async def counter(interaction):
"""Starts a counter for pressing."""
await interaction.send("Press!", view=Counter()) | Starts a counter for pressing. |
161,037 | from urllib.parse import quote_plus
import nextcord
from nextcord.ext import commands
class Google(nextcord.ui.View):
def __init__(self, query: str):
super().__init__()
# We need to quote the query string to make a valid URL. Discord will raise an error if it isn't valid.
query = quote_plus(query)
url = f"https://www.google.com/search?q={query}"
# Link buttons cannot be made with the decorator
# Therefore we have to manually create one.
# We add the quoted URL to the button, and add the button to the view.
self.add_item(nextcord.ui.Button(label="Click Here", url=url))
The provided code snippet includes necessary dependencies for implementing the `google` function. Write a Python function `async def google(interaction, query: str)` to solve the following problem:
Returns a google link for a query
Here is the function:
async def google(interaction, query: str):
"""Returns a google link for a query"""
await interaction.send(f"Google Result for: `{query}`", view=Google(query)) | Returns a google link for a query |
161,038 | import nextcord
from nextcord.ext import commands
class DropdownView(nextcord.ui.View):
def __init__(self):
super().__init__()
# Adds the dropdown to our view object.
self.add_item(Dropdown())
The provided code snippet includes necessary dependencies for implementing the `colour` function. Write a Python function `async def colour(interaction)` to solve the following problem:
Sends a message with our dropdown containing colours
Here is the function:
async def colour(interaction):
"""Sends a message with our dropdown containing colours"""
# Create the view containing our dropdown
view = DropdownView()
# Sending a message containing our view
await interaction.send("Pick your favourite colour:", view=view) | Sends a message with our dropdown containing colours |
161,039 | import nextcord
from nextcord.ext import application_checks, commands
class PersistentView(nextcord.ui.View):
def __init__(self):
super().__init__(timeout=None)
label="Green", style=nextcord.ButtonStyle.green, custom_id="persistent_view:green"
)
async def green(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message("This is green.", ephemeral=True)
label="Red", style=nextcord.ButtonStyle.red, custom_id="persistent_view:red"
)
async def red(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message("This is red.", ephemeral=True)
label="Grey", style=nextcord.ButtonStyle.grey, custom_id="persistent_view:grey"
)
async def grey(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message("This is grey.", ephemeral=True)
The provided code snippet includes necessary dependencies for implementing the `prepare` function. Write a Python function `async def prepare(interaction)` to solve the following problem:
Starts a persistent view.
Here is the function:
async def prepare(interaction):
"""Starts a persistent view."""
# In order for a persistent view to be listened to, it needs to be sent to an actual message.
# Call this method once just to store it somewhere.
# In a more complicated program you might fetch the message_id from a database for use later.
# However this is outside of the scope of this simple example.
await interaction.send("What's your favourite colour?", view=PersistentView()) | Starts a persistent view. |
161,040 | from typing import List
import nextcord
from nextcord.ext import commands
class TicTacToe(nextcord.ui.View):
# This tells the IDE or linter that all our children will be TicTacToeButtons
# This is not required
children: List[TicTacToeButton]
X = -1
O = 1
Tie = 2
def __init__(self):
super().__init__()
self.current_player = self.X
self.board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
]
# Our board is made up of 3 by 3 TicTacToeButtons
# The TicTacToeButton maintains the callbacks and helps steer
# the actual game.
for x in range(3):
for y in range(3):
self.add_item(TicTacToeButton(x, y))
# This method checks for the board winner -- it is used by the TicTacToeButton
def check_board_winner(self):
for across in self.board:
value = sum(across)
if value == 3:
return self.O
if value == -3:
return self.X
# Check vertical
for line in range(3):
value = self.board[0][line] + self.board[1][line] + self.board[2][line]
if value == 3:
return self.O
if value == -3:
return self.X
# Check diagonals
diag = self.board[0][2] + self.board[1][1] + self.board[2][0]
if diag == 3:
return self.O
if diag == -3:
return self.X
diag = self.board[0][0] + self.board[1][1] + self.board[2][2]
if diag == 3:
return self.O
if diag == -3:
return self.X
# If we're here, we need to check if a tie was made
if all(i != 0 for row in self.board for i in row):
return self.Tie
return None
The provided code snippet includes necessary dependencies for implementing the `tic` function. Write a Python function `async def tic(interaction)` to solve the following problem:
Starts a tic-tac-toe game with yourself.
Here is the function:
async def tic(interaction):
"""Starts a tic-tac-toe game with yourself."""
await interaction.send("Tic Tac Toe: X goes first", view=TicTacToe()) | Starts a tic-tac-toe game with yourself. |
161,041 | import nextcord
from nextcord.ext import commands
class Confirm(nextcord.ui.View):
def __init__(self):
super().__init__()
self.value = None
# When the confirm button is pressed, set the inner value to `True` and
# stop the View from listening to more input.
# We also send the user an ephemeral message that we're confirming their choice.
async def confirm(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message("Confirming", ephemeral=True)
self.value = True
self.stop()
# This one is similar to the confirmation button except sets the inner value to `False`
async def cancel(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message("Cancelling", ephemeral=True)
self.value = False
self.stop()
The provided code snippet includes necessary dependencies for implementing the `ask` function. Write a Python function `async def ask(interaction)` to solve the following problem:
Asks the user a question to confirm something.
Here is the function:
async def ask(interaction):
"""Asks the user a question to confirm something."""
# We create the view and assign it to a variable so we can wait for it later.
view = Confirm()
await interaction.send("Do you want to continue?", view=view)
# Wait for the View to stop listening for input...
await view.wait()
if view.value is None:
print("Timed out...")
elif view.value:
print("Confirmed...")
else:
print("Cancelled...") | Asks the user a question to confirm something. |
161,042 | from nextcord import Interaction
from nextcord.ext import commands
The provided code snippet includes necessary dependencies for implementing the `sub1` function. Write a Python function `async def sub1(interaction: Interaction)` to solve the following problem:
This is a subcommand of the '/main' slash command. It will appear in the menu as '/main sub1'.
Here is the function:
async def sub1(interaction: Interaction):
"""
This is a subcommand of the '/main' slash command.
It will appear in the menu as '/main sub1'.
"""
await interaction.response.send_message("This is subcommand 1!") | This is a subcommand of the '/main' slash command. It will appear in the menu as '/main sub1'. |
161,043 | from nextcord import Interaction
from nextcord.ext import commands
The provided code snippet includes necessary dependencies for implementing the `sub2` function. Write a Python function `async def sub2(interaction: Interaction)` to solve the following problem:
This is another subcommand of the '/main' slash command. It will appear in the menu as '/main sub2'.
Here is the function:
async def sub2(interaction: Interaction):
"""
This is another subcommand of the '/main' slash command.
It will appear in the menu as '/main sub2'.
"""
await interaction.response.send_message("This is subcommand 2!") | This is another subcommand of the '/main' slash command. It will appear in the menu as '/main sub2'. |
161,044 | from nextcord import Interaction
from nextcord.ext import commands
The provided code snippet includes necessary dependencies for implementing the `main_group` function. Write a Python function `async def main_group(interaction: Interaction)` to solve the following problem:
This is a subcommand group of the '/main' slash command. All subcommands of this group will be prefixed with '/main main_group'. This will never get called since it has subcommands.
Here is the function:
async def main_group(interaction: Interaction):
"""
This is a subcommand group of the '/main' slash command.
All subcommands of this group will be prefixed with '/main main_group'.
This will never get called since it has subcommands.
""" | This is a subcommand group of the '/main' slash command. All subcommands of this group will be prefixed with '/main main_group'. This will never get called since it has subcommands. |
161,045 | from nextcord import Interaction
from nextcord.ext import commands
The provided code snippet includes necessary dependencies for implementing the `subsub1` function. Write a Python function `async def subsub1(interaction: Interaction)` to solve the following problem:
This is a subcommand of the '/main main_group' subcommand group. It will appear in the menu as '/main main_group subsub1'.
Here is the function:
async def subsub1(interaction: Interaction):
"""
This is a subcommand of the '/main main_group' subcommand group.
It will appear in the menu as '/main main_group subsub1'.
"""
await interaction.response.send_message("This is a subcommand group's subcommand!") | This is a subcommand of the '/main main_group' subcommand group. It will appear in the menu as '/main main_group subsub1'. |
161,046 | from nextcord import Interaction
from nextcord.ext import commands
The provided code snippet includes necessary dependencies for implementing the `subsub2` function. Write a Python function `async def subsub2(interaction: Interaction)` to solve the following problem:
This is another subcommand of the '/main main_group' subcommand group. It will appear in the menu as '/main main_group subsub2'.
Here is the function:
async def subsub2(interaction: Interaction):
"""
This is another subcommand of the '/main main_group' subcommand group.
It will appear in the menu as '/main main_group subsub2'.
"""
await interaction.response.send_message("This is subcommand group subcommand 2!") | This is another subcommand of the '/main main_group' subcommand group. It will appear in the menu as '/main main_group subsub2'. |
161,047 | from nextcord import Interaction, SlashOption
from nextcord.ext import commands
async def your_favorite_dog(
interaction: Interaction,
dog: str = SlashOption(
name="dog",
description="Choose the best dog from this autocompleted list!",
),
):
# sends the autocompleted result
await interaction.response.send_message(f"Your favorite dog is {dog}!") | null |
161,048 | from nextcord import Interaction, SlashOption
from nextcord.ext import commands
list_of_dog_breeds = [
"German Shepard",
"Poodle",
"Pug",
"Shiba Inu",
]
async def favorite_dog(interaction: Interaction, dog: str):
if not dog:
# send the full autocomplete list
await interaction.response.send_autocomplete(list_of_dog_breeds)
return
# send a list of nearest matches from the list of dog breeds
get_near_dog = [breed for breed in list_of_dog_breeds if breed.lower().startswith(dog.lower())]
await interaction.response.send_autocomplete(get_near_dog) | null |
161,049 | import nextcord
from nextcord import Interaction, SlashOption
from nextcord.ext import commands
async def choose_a_number(
interaction: Interaction,
number: int = SlashOption(
name="picker",
description="The number you want",
choices={"one": 1, "two": 2, "three": 3},
),
):
await interaction.response.send_message(f"You chose {number}!") | null |
161,050 | import nextcord
from nextcord import Interaction, SlashOption
from nextcord.ext import commands
async def hi(
interaction: Interaction,
member: nextcord.Member = SlashOption(name="user", description="User to say hi to"),
):
await interaction.response.send_message(f"{interaction.user} just said hi to {member.mention}") | null |
161,051 | from nextcord import Interaction, Locale, SlashOption
from nextcord.ext import commands
async def hello_command(interaction: Interaction):
if interaction.locale == Locale.de:
await interaction.response.send_message("Hallo Welt!")
elif interaction.locale == Locale.fr:
await interaction.response.send_message("Bonjour le monde!")
elif interaction.locale == Locale.es_ES:
await interaction.response.send_message("¡Hola Mundo!")
else:
await interaction.response.send_message("Hello, world!") | null |
161,052 | from nextcord import Interaction, Locale, SlashOption
from nextcord.ext import commands
name="hello",
name_localizations={
Locale.de: "hallo",
Locale.fr: "bonjour",
Locale.es_ES: "hola",
},
description="Description of the command in English",
description_localizations={
Locale.de: "Beschreibung des Befehls auf Deutsch",
Locale.fr: "Description de la commande en français",
Locale.es_ES: "Descripción del comando en español",
},
async def choose_colour_command(
interaction: Interaction,
colour: str = SlashOption(
name="colour",
name_localizations={
Locale.en_US: "color",
Locale.de: "farbe",
Locale.fr: "couleur",
Locale.es_ES: "color",
},
description="Choose the colour",
description_localizations={
Locale.en_US: "Choose the color",
Locale.de: "Wählen Sie die Farbe",
Locale.fr: "Choisissez la couleur",
Locale.es_ES: "Elige el color",
},
choices=["Red", "Green", "Blue"],
choice_localizations={
"Red": {
Locale.de: "Rot",
Locale.fr: "Rouge",
Locale.es_ES: "Rojo",
},
"Green": {
Locale.de: "Grün",
Locale.fr: "Vert",
Locale.es_ES: "Verde",
},
"Blue": {
Locale.de: "Blau",
Locale.fr: "Bleu",
Locale.es_ES: "Azul",
},
},
),
):
if interaction.locale == Locale.en_US:
await interaction.response.send_message(f"You chose **`{colour}`** color")
elif interaction.locale == Locale.de:
await interaction.response.send_message(f"Du hast **`{colour}`** Farbe gewählt")
elif interaction.locale == Locale.fr:
await interaction.response.send_message(f"Tu as choisi la couleur **`{colour}`**")
elif interaction.locale == Locale.es_ES:
await interaction.response.send_message(f"Elegiste el color **`{colour}`**")
else:
await interaction.response.send_message(f"You chose **`{colour}`** colour") | null |
161,053 | import nextcord
from nextcord.ext import commands
async def member_info(interaction: nextcord.Interaction, member: nextcord.Member):
await interaction.response.send_message(f"Member: {member}") | null |
161,054 | import nextcord
from nextcord.ext import commands
async def my_message_command(interaction: nextcord.Interaction, message: nextcord.Message):
await interaction.response.send_message(f"Message: {message}") | null |
161,055 | from nextcord import Interaction, SlashOption
from nextcord.ext import commands
async def ping(interaction: Interaction):
await interaction.response.send_message("Pong!") | null |
161,056 | from nextcord import Interaction, SlashOption
from nextcord.ext import commands
async def echo(interaction: Interaction, arg: str = SlashOption(description="Message")):
await interaction.response.send_message(arg) | null |
161,057 | from nextcord import Interaction, SlashOption
from nextcord.ext import commands
async def enter_a_number(
interaction: Interaction,
number: int = SlashOption(description="Your number", required=False),
):
if not number:
await interaction.response.send_message("No number was specified!", ephemeral=True)
else:
await interaction.response.send_message(f"You chose {number}!") | null |
161,058 | import nextcord
from nextcord.ext import commands
class ApplicationCommandCog(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
async def my_slash_command(self, interaction: nextcord.Interaction):
await interaction.response.send_message("This is a slash command in a cog!")
async def my_user_command(self, interaction: nextcord.Interaction, member: nextcord.Member):
await interaction.response.send_message(f"Hello, {member}!")
async def my_message_command(
self, interaction: nextcord.Interaction, message: nextcord.Message
):
await interaction.response.send_message(f"{message}")
def setup(bot):
bot.add_cog(ApplicationCommandCog(bot)) | null |
161,059 | import random
import nextcord
from nextcord.ext import commands
async def headortails(ctx, answer):
if random.choice(["heads", "tails"]) == answer:
await ctx.reply("Congratulations")
else:
await ctx.reply("Sorry you lost") | null |
161,060 | import typing
import nextcord
from nextcord.ext import commands
The provided code snippet includes necessary dependencies for implementing the `secret` function. Write a Python function `async def secret(ctx)` to solve the following problem:
What is this "secret" you speak of?
Here is the function:
async def secret(ctx):
"""What is this "secret" you speak of?"""
if ctx.invoked_subcommand is None:
await ctx.send("Shh!", delete_after=5) | What is this "secret" you speak of? |
161,061 | import typing
import nextcord
from nextcord.ext import commands
def create_overwrites(ctx, *objects):
"""This is just a helper function that creates the overwrites for the
voice/text channels.
A `nextcord.PermissionOverwrite` allows you to determine the permissions
of an object, whether it be a `nextcord.Role` or a `nextcord.Member`.
In this case, the `view_channel` permission is being used to hide the channel
from being viewed by whoever does not meet the criteria, thus creating a
secret channel.
"""
# a dict comprehension is being utilised here to set the same permission overwrites
# for each `nextcord.Role` or `nextcord.Member`.
overwrites = {obj: nextcord.PermissionOverwrite(view_channel=True) for obj in objects}
# prevents the default role (@everyone) from viewing the channel
# if it isn't already allowed to view the channel.
overwrites.setdefault(ctx.guild.default_role, nextcord.PermissionOverwrite(view_channel=False))
# makes sure the client is always allowed to view the channel.
overwrites[ctx.guild.me] = nextcord.PermissionOverwrite(view_channel=True)
return overwrites
The provided code snippet includes necessary dependencies for implementing the `text` function. Write a Python function `async def text(ctx, name: str, *objects: typing.Union[nextcord.Role, nextcord.Member])` to solve the following problem:
This makes a text channel with a specified name that is only visible to roles or members that are specified.
Here is the function:
async def text(ctx, name: str, *objects: typing.Union[nextcord.Role, nextcord.Member]):
"""This makes a text channel with a specified name
that is only visible to roles or members that are specified.
"""
overwrites = create_overwrites(ctx, *objects)
await ctx.guild.create_text_channel(
name,
overwrites=overwrites,
topic="Top secret text channel. Any leakage of this channel may result in serious trouble.",
reason="Very secret business.",
) | This makes a text channel with a specified name that is only visible to roles or members that are specified. |
161,062 | import typing
import nextcord
from nextcord.ext import commands
def create_overwrites(ctx, *objects):
"""This is just a helper function that creates the overwrites for the
voice/text channels.
A `nextcord.PermissionOverwrite` allows you to determine the permissions
of an object, whether it be a `nextcord.Role` or a `nextcord.Member`.
In this case, the `view_channel` permission is being used to hide the channel
from being viewed by whoever does not meet the criteria, thus creating a
secret channel.
"""
# a dict comprehension is being utilised here to set the same permission overwrites
# for each `nextcord.Role` or `nextcord.Member`.
overwrites = {obj: nextcord.PermissionOverwrite(view_channel=True) for obj in objects}
# prevents the default role (@everyone) from viewing the channel
# if it isn't already allowed to view the channel.
overwrites.setdefault(ctx.guild.default_role, nextcord.PermissionOverwrite(view_channel=False))
# makes sure the client is always allowed to view the channel.
overwrites[ctx.guild.me] = nextcord.PermissionOverwrite(view_channel=True)
return overwrites
The provided code snippet includes necessary dependencies for implementing the `voice` function. Write a Python function `async def voice(ctx, name: str, *objects: typing.Union[nextcord.Role, nextcord.Member])` to solve the following problem:
This does the same thing as the `text` subcommand but instead creates a voice channel.
Here is the function:
async def voice(ctx, name: str, *objects: typing.Union[nextcord.Role, nextcord.Member]):
"""This does the same thing as the `text` subcommand
but instead creates a voice channel.
"""
overwrites = create_overwrites(ctx, *objects)
await ctx.guild.create_voice_channel(
name, overwrites=overwrites, reason="Very secret business."
) | This does the same thing as the `text` subcommand but instead creates a voice channel. |
161,063 | import typing
import nextcord
from nextcord.ext import commands
The provided code snippet includes necessary dependencies for implementing the `emoji` function. Write a Python function `async def emoji(ctx, emoji: nextcord.PartialEmoji, *roles: nextcord.Role)` to solve the following problem:
This clones a specified emoji that only specified roles are allowed to use.
Here is the function:
async def emoji(ctx, emoji: nextcord.PartialEmoji, *roles: nextcord.Role):
"""This clones a specified emoji that only specified roles
are allowed to use.
"""
# fetch the emoji asset and read it as bytes.
emoji_bytes = await emoji.read()
# the key parameter here is `roles`, which controls
# what roles are able to use the emoji.
await ctx.guild.create_custom_emoji(
name=emoji.name, image=emoji_bytes, roles=roles, reason="Very secret business."
) | This clones a specified emoji that only specified roles are allowed to use. |
161,064 | import nextcord
from nextcord.ext import commands
class Pet(nextcord.ui.Modal):
def __init__(self):
super().__init__(
"Your pet",
timeout=5 * 60, # 5 minutes
)
self.name = nextcord.ui.TextInput(
label="Your pet's name",
min_length=2,
max_length=50,
)
self.add_item(self.name)
self.description = nextcord.ui.TextInput(
label="Description",
style=nextcord.TextInputStyle.paragraph,
placeholder="Information that can help us recognise your pet",
required=False,
max_length=1800,
)
self.add_item(self.description)
async def callback(self, interaction: nextcord.Interaction) -> None:
response = f"{interaction.user.mention}'s favourite pet's name is {self.name.value}."
if self.description.value != "":
response += (
f"\nTheir pet can be recognized by this information:\n{self.description.value}"
)
await interaction.send(response)
async def send(interaction: nextcord.Interaction):
modal = Pet()
await interaction.response.send_modal(modal) | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.