code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
from __future__ import annotations from typing import List, Optional, Type, TypeVar, Union, TYPE_CHECKING from .asset import Asset from .utils import parse_time, snowflake_time, _get_as_snowflake from .object import Object from .mixins import Hashable from .enums import ChannelType, VerificationLevel, InviteTarget, try_enum from .appinfo import PartialAppInfo __all__ = ( 'PartialInviteChannel', 'PartialInviteGuild', 'Invite', ) if TYPE_CHECKING: from .types.invite import ( Invite as InvitePayload, InviteGuild as InviteGuildPayload, GatewayInvite as GatewayInvitePayload, ) from .types.channel import ( PartialChannel as InviteChannelPayload, ) from .state import ConnectionState from .guild import Guild from .abc import GuildChannel from .user import User InviteGuildType = Union[Guild, 'PartialInviteGuild', Object] InviteChannelType = Union[GuildChannel, 'PartialInviteChannel', Object] import datetime class PartialInviteChannel: """Represents a "partial" invite channel. This model will be given when the user is not part of the guild the :class:`Invite` resolves to. .. container:: operations .. describe:: x == y Checks if two partial channels are the same. .. describe:: x != y Checks if two partial channels are not the same. .. describe:: hash(x) Return the partial channel's hash. .. describe:: str(x) Returns the partial channel's name. Attributes ----------- name: :class:`str` The partial channel's name. id: :class:`int` The partial channel's ID. type: :class:`ChannelType` The partial channel's type. """ __slots__ = ('id', 'name', 'type') def __init__(self, data: InviteChannelPayload): self.id: int = int(data['id']) self.name: str = data['name'] self.type: ChannelType = try_enum(ChannelType, data['type']) def __str__(self) -> str: return self.name def __repr__(self) -> str: return f'<PartialInviteChannel id={self.id} name={self.name} type={self.type!r}>' @property def mention(self) -> str: """:class:`str`: The string that allows you to mention the channel.""" return f'<#{self.id}>' @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" return snowflake_time(self.id) class PartialInviteGuild: """Represents a "partial" invite guild. This model will be given when the user is not part of the guild the :class:`Invite` resolves to. .. container:: operations .. describe:: x == y Checks if two partial guilds are the same. .. describe:: x != y Checks if two partial guilds are not the same. .. describe:: hash(x) Return the partial guild's hash. .. describe:: str(x) Returns the partial guild's name. Attributes ----------- name: :class:`str` The partial guild's name. id: :class:`int` The partial guild's ID. verification_level: :class:`VerificationLevel` The partial guild's verification level. features: List[:class:`str`] A list of features the guild has. See :attr:`Guild.features` for more information. description: Optional[:class:`str`] The partial guild's description. """ __slots__ = ('_state', 'features', '_icon', '_banner', 'id', 'name', '_splash', 'verification_level', 'description') def __init__(self, state: ConnectionState, data: InviteGuildPayload, id: int): self._state: ConnectionState = state self.id: int = id self.name: str = data['name'] self.features: List[str] = data.get('features', []) self._icon: Optional[str] = data.get('icon') self._banner: Optional[str] = data.get('banner') self._splash: Optional[str] = data.get('splash') self.verification_level: VerificationLevel = try_enum(VerificationLevel, data.get('verification_level')) self.description: Optional[str] = data.get('description') def __str__(self) -> str: return self.name def __repr__(self) -> str: return ( f'<{self.__class__.__name__} id={self.id} name={self.name!r} features={self.features} ' f'description={self.description!r}>' ) @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the guild's creation time in UTC.""" return snowflake_time(self.id) @property 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) @property 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') @property 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') I = TypeVar('I', bound='Invite') class Invite(Hashable): r"""Represents a Discord :class:`Guild` or :class:`abc.GuildChannel` invite. Depending on the way this object was created, some of the attributes can have a value of ``None``. .. container:: operations .. describe:: x == y Checks if two invites are equal. .. describe:: x != y Checks if two invites are not equal. .. describe:: hash(x) Returns the invite hash. .. describe:: str(x) Returns the invite URL. The following table illustrates what methods will obtain the attributes: +------------------------------------+------------------------------------------------------------+ | Attribute | Method | +====================================+============================================================+ | :attr:`max_age` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+------------------------------------------------------------+ | :attr:`max_uses` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+------------------------------------------------------------+ | :attr:`created_at` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+------------------------------------------------------------+ | :attr:`temporary` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+------------------------------------------------------------+ | :attr:`uses` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+------------------------------------------------------------+ | :attr:`approximate_member_count` | :meth:`Client.fetch_invite` with `with_counts` enabled | +------------------------------------+------------------------------------------------------------+ | :attr:`approximate_presence_count` | :meth:`Client.fetch_invite` with `with_counts` enabled | +------------------------------------+------------------------------------------------------------+ | :attr:`expires_at` | :meth:`Client.fetch_invite` with `with_expiration` enabled | +------------------------------------+------------------------------------------------------------+ If it's not in the table above then it is available by all methods. Attributes ----------- max_age: :class:`int` How long before the invite expires in seconds. A value of ``0`` indicates that it doesn't expire. code: :class:`str` The URL fragment used for the invite. guild: Optional[Union[:class:`Guild`, :class:`Object`, :class:`PartialInviteGuild`]] The guild the invite is for. Can be ``None`` if it's from a group direct message. revoked: :class:`bool` Indicates if the invite has been revoked. created_at: :class:`datetime.datetime` An aware UTC datetime object denoting the time the invite was created. temporary: :class:`bool` Indicates that the invite grants temporary membership. If ``True``, members who joined via this invite will be kicked upon disconnect. uses: :class:`int` How many times the invite has been used. max_uses: :class:`int` How many times the invite can be used. A value of ``0`` indicates that it has unlimited uses. inviter: Optional[:class:`User`] The user who created the invite. approximate_member_count: Optional[:class:`int`] The approximate number of members in the guild. 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. expires_at: Optional[:class:`datetime.datetime`] The expiration date of the invite. If the value is ``None`` when received through `Client.fetch_invite` with `with_expiration` enabled, the invite will never expire. .. versionadded:: 2.0 channel: Union[:class:`abc.GuildChannel`, :class:`Object`, :class:`PartialInviteChannel`] The channel the invite is for. target_type: :class:`InviteTarget` The type of target for the voice channel invite. .. versionadded:: 2.0 target_user: Optional[:class:`User`] The user whose stream to display for this invite, if any. .. versionadded:: 2.0 target_application: Optional[:class:`PartialAppInfo`] The embedded application the invite targets, if any. .. versionadded:: 2.0 """ __slots__ = ( 'max_age', 'code', 'guild', 'revoked', 'created_at', 'uses', 'temporary', 'max_uses', 'inviter', 'channel', 'target_user', 'target_type', '_state', 'approximate_member_count', 'approximate_presence_count', 'target_application', 'expires_at', ) BASE = 'https://discord.gg' def __init__( self, *, state: ConnectionState, data: InvitePayload, guild: Optional[Union[PartialInviteGuild, Guild]] = None, channel: Optional[Union[PartialInviteChannel, GuildChannel]] = None, ): self._state: ConnectionState = state self.max_age: Optional[int] = data.get('max_age') self.code: str = data['code'] self.guild: Optional[InviteGuildType] = self._resolve_guild(data.get('guild'), guild) self.revoked: Optional[bool] = data.get('revoked') self.created_at: Optional[datetime.datetime] = parse_time(data.get('created_at')) self.temporary: Optional[bool] = data.get('temporary') self.uses: Optional[int] = data.get('uses') self.max_uses: Optional[int] = data.get('max_uses') self.approximate_presence_count: Optional[int] = data.get('approximate_presence_count') self.approximate_member_count: Optional[int] = data.get('approximate_member_count') expires_at = data.get('expires_at', None) self.expires_at: Optional[datetime.datetime] = parse_time(expires_at) if expires_at else None inviter_data = data.get('inviter') self.inviter: Optional[User] = None if inviter_data is None else self._state.create_user(inviter_data) self.channel: Optional[InviteChannelType] = self._resolve_channel(data.get('channel'), channel) target_user_data = data.get('target_user') self.target_user: Optional[User] = None if target_user_data is None else self._state.create_user(target_user_data) self.target_type: InviteTarget = try_enum(InviteTarget, data.get("target_type", 0)) application = data.get('target_application') self.target_application: Optional[PartialAppInfo] = ( PartialAppInfo(data=application, state=state) if application else None ) @classmethod def from_incomplete(cls: Type[I], *, state: ConnectionState, data: InvitePayload) -> I: guild: Optional[Union[Guild, PartialInviteGuild]] try: guild_data = data['guild'] except KeyError: # If we're here, then this is a group DM guild = None else: guild_id = int(guild_data['id']) guild = state._get_guild(guild_id) if guild is None: # If it's not cached, then it has to be a partial guild guild = PartialInviteGuild(state, guild_data, guild_id) # As far as I know, invites always need a channel # So this should never raise. channel: Union[PartialInviteChannel, GuildChannel] = PartialInviteChannel(data['channel']) if guild is not None and not isinstance(guild, PartialInviteGuild): # Upgrade the partial data if applicable channel = guild.get_channel(channel.id) or channel return cls(state=state, data=data, guild=guild, channel=channel) @classmethod def from_gateway(cls: Type[I], *, state: ConnectionState, data: GatewayInvitePayload) -> I: guild_id: Optional[int] = _get_as_snowflake(data, 'guild_id') guild: Optional[Union[Guild, Object]] = state._get_guild(guild_id) channel_id = int(data['channel_id']) if guild is not None: channel = guild.get_channel(channel_id) or Object(id=channel_id) # type: ignore else: guild = Object(id=guild_id) if guild_id is not None else None channel = Object(id=channel_id) return cls(state=state, data=data, guild=guild, channel=channel) # type: ignore def _resolve_guild( self, data: Optional[InviteGuildPayload], guild: Optional[Union[Guild, PartialInviteGuild]] = None, ) -> Optional[InviteGuildType]: if guild is not None: return guild if data is None: return None guild_id = int(data['id']) return PartialInviteGuild(self._state, data, guild_id) def _resolve_channel( self, data: Optional[InviteChannelPayload], channel: Optional[Union[PartialInviteChannel, GuildChannel]] = None, ) -> Optional[InviteChannelType]: if channel is not None: return channel if data is None: return None return PartialInviteChannel(data) def __str__(self) -> str: return self.url def __repr__(self) -> str: return ( f'<Invite code={self.code!r} guild={self.guild!r} ' f'online={self.approximate_presence_count} ' f'members={self.approximate_member_count}>' ) def __hash__(self) -> int: return hash(self.code) @property def id(self) -> str: """:class:`str`: Returns the proper code portion of the invite.""" return self.code @property def url(self) -> str: """:class:`str`: A property that retrieves the invite URL.""" return self.BASE + '/' + self.code async def delete(self, *, reason: Optional[str] = None): """|coro| Revokes the instant invite. You must have the :attr:`~Permissions.manage_channels` permission to do this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this invite. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to revoke invites. NotFound The invite is invalid or expired. HTTPException Revoking the invite failed. """ await self._state.http.delete_invite(self.code, reason=reason)
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/invite.py
invite.py
from __future__ import annotations from typing import Callable, Dict, Iterable, List, Optional, Union, TYPE_CHECKING import time import asyncio from .mixins import Hashable from .abc import Messageable from .enums import ChannelType, try_enum from .errors import ClientException from .utils import MISSING, parse_time, _get_as_snowflake __all__ = ( 'Thread', 'ThreadMember', ) if TYPE_CHECKING: from .types.threads import ( Thread as ThreadPayload, ThreadMember as ThreadMemberPayload, ThreadMetadata, ThreadArchiveDuration, ) from .types.snowflake import SnowflakeList from .guild import Guild from .channel import TextChannel, CategoryChannel from .member import Member from .message import Message, PartialMessage from .abc import Snowflake, SnowflakeTime from .role import Role from .permissions import Permissions from .state import ConnectionState class Thread(Messageable, Hashable): """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. """ __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', ) def __init__(self, *, guild: Guild, state: ConnectionState, data: ThreadPayload): 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): 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']) try: member = data['member'] except KeyError: self.me = None else: self.me = ThreadMember(self, member) def _unroll_metadata(self, data: ThreadMetadata): 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) def _update(self, data): try: self.name = data['name'] except KeyError: pass self.slowmode_delay = data.get('rate_limit_per_user', 0) try: self._unroll_metadata(data['thread_metadata']) except KeyError: pass @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return self._type @property def parent(self) -> Optional[TextChannel]: """Optional[:class:`TextChannel`]: The parent channel this thread belongs to.""" return self.guild.get_channel(self.parent_id) # type: ignore @property def owner(self) -> Optional[Member]: """Optional[:class:`Member`]: The member this thread belongs to.""" return self.guild.get_member(self.owner_id) @property def mention(self) -> str: """:class:`str`: The string that allows you to mention the thread.""" return f'<#{self.id}>' @property 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()) @property 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 @property 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 @property 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 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:`~discord.Member` or :class:`~discord.Role`. Since threads do not have their own permissions, they inherit them from the parent channel. This is a convenience method for calling :meth:`~discord.TextChannel.permissions_for` on the parent channel. Parameters ---------- obj: Union[:class:`~discord.Member`, :class:`~discord.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:`~discord.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 m: 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]): 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, ) -> 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``. 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 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): """|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): """|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): """|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): """|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): """|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) class ThreadMember(Hashable): """Represents a Discord thread member. .. container:: operations .. describe:: x == y Checks if two thread members are equal. .. describe:: x != y Checks if two thread members are not equal. .. describe:: hash(x) Returns the thread member's hash. .. describe:: str(x) Returns the thread member's name. .. versionadded:: 2.0 Attributes ----------- id: :class:`int` The thread member's ID. thread_id: :class:`int` The thread's ID. joined_at: :class:`datetime.datetime` The time the member joined the thread in UTC. """ __slots__ = ( 'id', 'thread_id', 'joined_at', 'flags', '_state', 'parent', ) def __init__(self, parent: Thread, data: ThreadMemberPayload): self.parent = parent self._state = parent._state self._from_data(data) def __repr__(self) -> str: return f'<ThreadMember id={self.id} thread_id={self.thread_id} joined_at={self.joined_at!r}>' def _from_data(self, data: ThreadMemberPayload): try: self.id = int(data['user_id']) except KeyError: assert self._state.self_id is not None self.id = self._state.self_id try: self.thread_id = int(data['id']) except KeyError: self.thread_id = self.parent.id self.joined_at = parse_time(data['join_timestamp']) self.flags = data['flags'] @property def thread(self) -> Thread: """:class:`Thread`: The thread this member belongs to.""" return self.parent
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/threads.py
threads.py
from __future__ import annotations import time import asyncio from typing import ( Any, Callable, Dict, Iterable, List, Mapping, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Union, overload, ) import datetime import discord.abc from .permissions import PermissionOverwrite, Permissions from .enums import ChannelType, StagePrivacyLevel, try_enum, VoiceRegion, VideoQualityMode from .mixins import Hashable from .object import Object from . import utils from .utils import MISSING from .asset import Asset from .errors import ClientException, InvalidArgument from .stage_instance import StageInstance from .threads import Thread from .iterators import ArchivedThreadIterator __all__ = ( 'TextChannel', 'VoiceChannel', 'StageChannel', 'DMChannel', 'CategoryChannel', 'StoreChannel', 'GroupChannel', 'PartialMessageable', ) if TYPE_CHECKING: from .types.threads import ThreadArchiveDuration from .role import Role from .member import Member, VoiceState from .abc import Snowflake, SnowflakeTime from .message import Message, PartialMessage from .webhook import Webhook from .state import ConnectionState from .user import ClientUser, User, BaseUser from .guild import Guild, GuildChannel as GuildChannelType from .types.channel import ( TextChannel as TextChannelPayload, VoiceChannel as VoiceChannelPayload, StageChannel as StageChannelPayload, DMChannel as DMChannelPayload, CategoryChannel as CategoryChannelPayload, StoreChannel as StoreChannelPayload, GroupDMChannel as GroupChannelPayload, ) from .types.snowflake import SnowflakeList async def _single_delete_strategy(messages: Iterable[Message]): for m in messages: await m.delete() class TextChannel(discord.abc.Messageable, discord.abc.GuildChannel, Hashable): """Represents a Discord guild text channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns the channel's name. Attributes ----------- name: :class:`str` The channel name. guild: :class:`Guild` The guild the channel belongs to. id: :class:`int` The channel ID. category_id: Optional[:class:`int`] The category channel ID this channel belongs to, if applicable. topic: Optional[:class:`str`] The channel's topic. ``None`` if it doesn't exist. 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. last_message_id: Optional[:class:`int`] The last message ID of the message sent to this channel. 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 channel. A value of `0` denotes that it is disabled. Bots and users with :attr:`~Permissions.manage_channels` or :attr:`~Permissions.manage_messages` bypass slowmode. nsfw: :class:`bool` If the channel is marked as "not safe for work". .. note:: To check if the channel or the guild of that channel are marked as NSFW, consider :meth:`is_nsfw` instead. default_auto_archive_duration: :class:`int` The default auto archive duration in minutes for threads created in this channel. .. versionadded:: 2.0 """ __slots__ = ( 'name', 'id', 'guild', 'topic', '_state', 'nsfw', 'category_id', 'position', 'slowmode_delay', '_overwrites', '_type', 'last_message_id', 'default_auto_archive_duration', ) def __init__(self, *, state: ConnectionState, guild: Guild, data: TextChannelPayload): self._state: ConnectionState = state self.id: int = int(data['id']) self._type: int = data['type'] self._update(guild, data) def __repr__(self) -> str: attrs = [ ('id', self.id), ('name', self.name), ('position', self.position), ('nsfw', self.nsfw), ('news', self.is_news()), ('category_id', self.category_id), ] joined = ' '.join('%s=%r' % t for t in attrs) return f'<{self.__class__.__name__} {joined}>' def _update(self, guild: Guild, data: TextChannelPayload) -> None: self.guild: Guild = guild self.name: str = data['name'] self.category_id: Optional[int] = utils._get_as_snowflake(data, 'parent_id') self.topic: Optional[str] = data.get('topic') self.position: int = data['position'] self.nsfw: bool = data.get('nsfw', False) # Does this need coercion into `int`? No idea yet. self.slowmode_delay: int = data.get('rate_limit_per_user', 0) self.default_auto_archive_duration: ThreadArchiveDuration = data.get('default_auto_archive_duration', 1440) self._type: int = data.get('type', self._type) self.last_message_id: Optional[int] = utils._get_as_snowflake(data, 'last_message_id') self._fill_overwrites(data) async def _get_channel(self): return self @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return try_enum(ChannelType, self._type) @property def _sorting_bucket(self) -> int: return ChannelType.text.value @utils.copy_doc(discord.abc.GuildChannel.permissions_for) def permissions_for(self, obj: Union[Member, Role], /) -> Permissions: base = super().permissions_for(obj) # text channels do not have voice related permissions denied = Permissions.voice() base.value &= ~denied.value return base @property def members(self) -> List[Member]: """List[:class:`Member`]: Returns all members that can see this channel.""" return [m for m in self.guild.members if self.permissions_for(m).read_messages] @property def threads(self) -> List[Thread]: """List[:class:`Thread`]: Returns all the threads that you can see. .. versionadded:: 2.0 """ return [thread for thread in self.guild._threads.values() if thread.parent_id == self.id] def is_nsfw(self) -> bool: """:class:`bool`: Checks if the channel is NSFW.""" return self.nsfw def is_news(self) -> bool: """:class:`bool`: Checks if the channel is a news channel.""" return self._type == ChannelType.news.value @property 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 @overload async def edit( self, *, reason: Optional[str] = ..., name: str = ..., topic: str = ..., position: int = ..., nsfw: bool = ..., sync_permissions: bool = ..., category: Optional[CategoryChannel] = ..., slowmode_delay: int = ..., default_auto_archive_duration: ThreadArchiveDuration = ..., type: ChannelType = ..., overwrites: Mapping[Union[Role, Member, Snowflake], PermissionOverwrite] = ..., ) -> Optional[TextChannel]: ... @overload async def edit(self) -> Optional[TextChannel]: ... async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionchanged:: 1.3 The ``overwrites`` keyword-only parameter was added. .. versionchanged:: 1.4 The ``type`` keyword-only parameter was added. .. versionchanged:: 2.0 Edits are no longer in-place, the newly edited channel is returned instead. Parameters ---------- name: :class:`str` The new channel name. topic: :class:`str` The new channel's topic. position: :class:`int` The new channel's position. nsfw: :class:`bool` To mark the channel as NSFW or not. sync_permissions: :class:`bool` Whether to sync permissions with the channel's new or pre-existing category. Defaults to ``False``. category: Optional[:class:`CategoryChannel`] The new category for this channel. Can be ``None`` to remove the category. slowmode_delay: :class:`int` Specifies the slowmode rate limit for user in this channel, in seconds. A value of `0` disables slowmode. The maximum value possible is `21600`. type: :class:`ChannelType` Change the type of this text channel. Currently, only conversion between :attr:`ChannelType.text` and :attr:`ChannelType.news` is supported. This is only available to guilds that contain ``NEWS`` in :attr:`Guild.features`. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. overwrites: :class:`Mapping` A :class:`Mapping` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. default_auto_archive_duration: :class:`int` The new default auto archive duration in minutes for threads created in this channel. Must be one of ``60``, ``1440``, ``4320``, or ``10080``. Raises ------ InvalidArgument If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form. Forbidden You do not have permissions to edit the channel. HTTPException Editing the channel failed. Returns -------- Optional[:class:`.TextChannel`] The newly edited text channel. If the edit was only positional then ``None`` is returned instead. """ payload = await self._edit(options, reason=reason) if payload is not None: # the payload will always be the proper channel payload return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> TextChannel: return await self._clone_impl( {'topic': self.topic, 'nsfw': self.nsfw, 'rate_limit_per_user': self.slowmode_delay}, name=name, reason=reason ) 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. 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. 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: int = 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. 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 channel.purge(limit=100, check=is_me) await channel.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 m: 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 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 webhooks(self) -> List[Webhook]: """|coro| Gets the list of webhooks from this channel. 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 channel. """ from .webhook import Webhook data = await self._state.http.channel_webhooks(self.id) return [Webhook.from_state(d, state=self._state) for d in data] async def create_webhook(self, *, name: str, avatar: Optional[bytes] = None, reason: Optional[str] = None) -> Webhook: """|coro| Creates a webhook for this channel. Requires :attr:`~.Permissions.manage_webhooks` permissions. .. versionchanged:: 1.1 Added the ``reason`` keyword-only parameter. Parameters ------------- name: :class:`str` The webhook's name. avatar: Optional[:class:`bytes`] A :term:`py:bytes-like object` representing the webhook's default avatar. This operates similarly to :meth:`~ClientUser.edit`. reason: Optional[:class:`str`] The reason for creating this webhook. Shows up in the audit logs. Raises ------- HTTPException Creating the webhook failed. Forbidden You do not have permissions to create a webhook. Returns -------- :class:`Webhook` The created webhook. """ from .webhook import Webhook if avatar is not None: avatar = utils._bytes_to_base64_data(avatar) # type: ignore data = await self._state.http.create_webhook(self.id, name=str(name), avatar=avatar, reason=reason) return Webhook.from_state(data, state=self._state) async def follow(self, *, destination: TextChannel, reason: Optional[str] = None) -> Webhook: """ Follows a channel using a webhook. Only news channels can be followed. .. note:: The webhook returned will not provide a token to do webhook actions, as Discord does not provide it. .. versionadded:: 1.3 Parameters ----------- destination: :class:`TextChannel` The channel you would like to follow from. reason: Optional[:class:`str`] The reason for following the channel. Shows up on the destination guild's audit log. .. versionadded:: 1.4 Raises ------- HTTPException Following the channel failed. Forbidden You do not have the permissions to create a webhook. Returns -------- :class:`Webhook` The created webhook. """ if not self.is_news(): raise ClientException('The channel must be a news channel.') if not isinstance(destination, TextChannel): raise InvalidArgument(f'Expected TextChannel received {destination.__class__.__name__}') from .webhook import Webhook data = await self._state.http.follow_webhook(self.id, webhook_channel_id=destination.id, reason=reason) return Webhook._as_follower(data, channel=destination, user=self._state.user) 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:: 1.6 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 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.guild.get_thread(thread_id) async def create_thread( self, *, name: str, message: Optional[Snowflake] = None, auto_archive_duration: ThreadArchiveDuration = MISSING, type: Optional[ChannelType] = None, reason: Optional[str] = None, ) -> Thread: """|coro| Creates a thread in this text channel. To create a public thread, you must have :attr:`~discord.Permissions.create_public_threads`. For a private thread, :attr:`~discord.Permissions.create_private_threads` is needed instead. .. versionadded:: 2.0 Parameters ----------- name: :class:`str` The name of the thread. message: Optional[:class:`abc.Snowflake`] A snowflake representing the message to create the thread with. If ``None`` is passed then a private thread is created. Defaults to ``None``. auto_archive_duration: :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. type: Optional[:class:`ChannelType`] The type of thread to create. If a ``message`` is passed then this parameter is ignored, as a thread created with a message is always a public thread. By default this creates a private thread if this is ``None``. reason: :class:`str` The reason for creating a new thread. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to create a thread. HTTPException Starting the thread failed. Returns -------- :class:`Thread` The created thread """ if type is None: type = ChannelType.private_thread if message is None: data = await self._state.http.start_thread_without_message( self.id, name=name, auto_archive_duration=auto_archive_duration or self.default_auto_archive_duration, type=type.value, reason=reason, ) else: data = await self._state.http.start_thread_with_message( self.id, message.id, name=name, auto_archive_duration=auto_archive_duration or self.default_auto_archive_duration, reason=reason, ) return Thread(guild=self.guild, state=self._state, data=data) def archived_threads( self, *, private: bool = False, joined: bool = False, limit: Optional[int] = 50, before: Optional[Union[Snowflake, datetime.datetime]] = None, ) -> ArchivedThreadIterator: """Returns an :class:`~discord.AsyncIterator` that iterates over all archived threads in the guild. You must have :attr:`~Permissions.read_message_history` to use this. If iterating over private threads then :attr:`~Permissions.manage_threads` is also required. .. versionadded:: 2.0 Parameters ----------- limit: Optional[:class:`bool`] The number of threads to retrieve. If ``None``, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation. before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Retrieve archived channels before the given date or ID. private: :class:`bool` Whether to retrieve private archived threads. joined: :class:`bool` Whether to retrieve private archived threads that you've joined. You cannot set ``joined`` to ``True`` and ``private`` to ``False``. Raises ------ Forbidden You do not have permissions to get archived threads. HTTPException The request to get the archived threads failed. Yields ------- :class:`Thread` The archived threads. """ return ArchivedThreadIterator(self.id, self.guild, limit=limit, joined=joined, private=private, before=before) class VocalGuildChannel(discord.abc.Connectable, discord.abc.GuildChannel, Hashable): __slots__ = ( 'name', 'id', 'guild', 'bitrate', 'user_limit', '_state', 'position', '_overwrites', 'category_id', 'rtc_region', 'video_quality_mode', ) def __init__(self, *, state: ConnectionState, guild: Guild, data: Union[VoiceChannelPayload, StageChannelPayload]): self._state: ConnectionState = state self.id: int = int(data['id']) self._update(guild, data) def _get_voice_client_key(self) -> Tuple[int, str]: return self.guild.id, 'guild_id' def _get_voice_state_pair(self) -> Tuple[int, int]: return self.guild.id, self.id def _update(self, guild: Guild, data: Union[VoiceChannelPayload, StageChannelPayload]) -> None: self.guild = guild self.name: str = data['name'] rtc = data.get('rtc_region') self.rtc_region: Optional[VoiceRegion] = try_enum(VoiceRegion, rtc) if rtc is not None else None self.video_quality_mode: VideoQualityMode = try_enum(VideoQualityMode, data.get('video_quality_mode', 1)) self.category_id: Optional[int] = utils._get_as_snowflake(data, 'parent_id') self.position: int = data['position'] self.bitrate: int = data.get('bitrate') self.user_limit: int = data.get('user_limit') self._fill_overwrites(data) @property def _sorting_bucket(self) -> int: return ChannelType.voice.value @property def members(self) -> List[Member]: """List[:class:`Member`]: Returns all members that are currently inside this voice channel.""" ret = [] for user_id, state in self.guild._voice_states.items(): if state.channel and state.channel.id == self.id: member = self.guild.get_member(user_id) if member is not None: ret.append(member) return ret @property def voice_states(self) -> Dict[int, VoiceState]: """Returns a mapping of member IDs who have voice states in this channel. .. versionadded:: 1.3 .. note:: This function is intentionally low level to replace :attr:`members` when the member cache is unavailable. Returns -------- Mapping[:class:`int`, :class:`VoiceState`] The mapping of member ID to a voice state. """ # fmt: off return { key: value for key, value in self.guild._voice_states.items() if value.channel and value.channel.id == self.id } # fmt: on @utils.copy_doc(discord.abc.GuildChannel.permissions_for) def permissions_for(self, obj: Union[Member, Role], /) -> Permissions: base = super().permissions_for(obj) # voice channels cannot be edited by people who can't connect to them # It also implicitly denies all other voice perms if not base.connect: denied = Permissions.voice() denied.update(manage_channels=True, manage_roles=True) base.value &= ~denied.value return base class VoiceChannel(VocalGuildChannel): """Represents a Discord guild voice channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns the channel's name. Attributes ----------- name: :class:`str` The channel name. guild: :class:`Guild` The guild the channel belongs to. id: :class:`int` The channel ID. category_id: Optional[:class:`int`] The category channel ID this channel belongs to, if applicable. 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 """ __slots__ = () def __repr__(self) -> str: attrs = [ ('id', self.id), ('name', self.name), ('rtc_region', self.rtc_region), ('position', self.position), ('bitrate', self.bitrate), ('video_quality_mode', self.video_quality_mode), ('user_limit', self.user_limit), ('category_id', self.category_id), ] joined = ' '.join('%s=%r' % t for t in attrs) return f'<{self.__class__.__name__} {joined}>' @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.voice @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> VoiceChannel: return await self._clone_impl({'bitrate': self.bitrate, 'user_limit': self.user_limit}, name=name, reason=reason) @overload async def edit( self, *, name: str = ..., bitrate: int = ..., user_limit: int = ..., position: int = ..., sync_permissions: int = ..., category: Optional[CategoryChannel] = ..., overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = ..., rtc_region: Optional[VoiceRegion] = ..., video_quality_mode: VideoQualityMode = ..., reason: Optional[str] = ..., ) -> Optional[VoiceChannel]: ... @overload async def edit(self) -> Optional[VoiceChannel]: ... async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionchanged:: 1.3 The ``overwrites`` keyword-only parameter was added. .. versionchanged:: 2.0 Edits are no longer in-place, the newly edited channel is returned instead. Parameters ---------- name: :class:`str` The new channel's name. bitrate: :class:`int` The new channel's bitrate. user_limit: :class:`int` The new channel's user limit. position: :class:`int` The new channel's position. sync_permissions: :class:`bool` Whether to sync permissions with the channel's new or pre-existing category. Defaults to ``False``. category: Optional[:class:`CategoryChannel`] The new category for this channel. Can be ``None`` to remove the category. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. overwrites: :class:`Mapping` A :class:`Mapping` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. rtc_region: Optional[:class:`VoiceRegion`] The new 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 Raises ------ InvalidArgument If the permission overwrite information is not in proper form. Forbidden You do not have permissions to edit the channel. HTTPException Editing the channel failed. Returns -------- Optional[:class:`.VoiceChannel`] The newly edited voice channel. If the edit was only positional then ``None`` is returned instead. """ payload = await self._edit(options, reason=reason) if payload is not None: # the payload will always be the proper channel payload return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore class StageChannel(VocalGuildChannel): """Represents a Discord guild stage channel. .. versionadded:: 1.7 .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns the channel's name. Attributes ----------- name: :class:`str` The channel name. guild: :class:`Guild` The guild the channel belongs to. id: :class:`int` The channel ID. topic: Optional[:class:`str`] The channel's topic. ``None`` if it isn't set. category_id: Optional[:class:`int`] The category channel ID this channel belongs to, if applicable. 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 stage channel. rtc_region: Optional[:class:`VoiceRegion`] The region for the stage channel's voice communication. A value of ``None`` indicates automatic voice region detection. video_quality_mode: :class:`VideoQualityMode` The camera video quality for the stage channel's participants. .. versionadded:: 2.0 """ __slots__ = ('topic',) def __repr__(self) -> str: attrs = [ ('id', self.id), ('name', self.name), ('topic', self.topic), ('rtc_region', self.rtc_region), ('position', self.position), ('bitrate', self.bitrate), ('video_quality_mode', self.video_quality_mode), ('user_limit', self.user_limit), ('category_id', self.category_id), ] joined = ' '.join('%s=%r' % t for t in attrs) return f'<{self.__class__.__name__} {joined}>' def _update(self, guild: Guild, data: StageChannelPayload) -> None: super()._update(guild, data) self.topic = data.get('topic') @property def requesting_to_speak(self) -> List[Member]: """List[:class:`Member`]: A list of members who are requesting to speak in the stage channel.""" return [member for member in self.members if member.voice and member.voice.requested_to_speak_at is not None] @property def speakers(self) -> List[Member]: """List[:class:`Member`]: A list of members who have been permitted to speak in the stage channel. .. versionadded:: 2.0 """ return [ member for member in self.members if member.voice and not member.voice.suppress and member.voice.requested_to_speak_at is None ] @property def listeners(self) -> List[Member]: """List[:class:`Member`]: A list of members who are listening in the stage channel. .. versionadded:: 2.0 """ return [member for member in self.members if member.voice and member.voice.suppress] @property def moderators(self) -> List[Member]: """List[:class:`Member`]: A list of members who are moderating the stage channel. .. versionadded:: 2.0 """ required_permissions = Permissions.stage_moderator() return [member for member in self.members if self.permissions_for(member) >= required_permissions] @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.stage_voice @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> StageChannel: return await self._clone_impl({}, name=name, reason=reason) @property def instance(self) -> Optional[StageInstance]: """Optional[:class:`StageInstance`]: The running stage instance of the stage channel. .. versionadded:: 2.0 """ return utils.get(self.guild.stage_instances, channel_id=self.id) async def create_instance( self, *, topic: str, privacy_level: StagePrivacyLevel = MISSING, reason: Optional[str] = None ) -> StageInstance: """|coro| Create a stage instance. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionadded:: 2.0 Parameters ----------- topic: :class:`str` The stage instance's topic. privacy_level: :class:`StagePrivacyLevel` The stage instance's privacy level. Defaults to :attr:`StagePrivacyLevel.guild_only`. reason: :class:`str` The reason the stage instance was created. Shows up on the audit log. Raises ------ InvalidArgument If the ``privacy_level`` parameter is not the proper type. Forbidden You do not have permissions to create a stage instance. HTTPException Creating a stage instance failed. Returns -------- :class:`StageInstance` The newly created stage instance. """ payload: Dict[str, Any] = {'channel_id': self.id, 'topic': topic} if privacy_level is not MISSING: if not isinstance(privacy_level, StagePrivacyLevel): raise InvalidArgument('privacy_level field must be of type PrivacyLevel') payload['privacy_level'] = privacy_level.value data = await self._state.http.create_stage_instance(**payload, reason=reason) return StageInstance(guild=self.guild, state=self._state, data=data) async def fetch_instance(self) -> StageInstance: """|coro| Gets the running :class:`StageInstance`. .. versionadded:: 2.0 Raises ------- :exc:`.NotFound` The stage instance or channel could not be found. :exc:`.HTTPException` Getting the stage instance failed. Returns -------- :class:`StageInstance` The stage instance. """ data = await self._state.http.get_stage_instance(self.id) return StageInstance(guild=self.guild, state=self._state, data=data) @overload async def edit( self, *, name: str = ..., topic: Optional[str] = ..., position: int = ..., sync_permissions: int = ..., category: Optional[CategoryChannel] = ..., overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = ..., rtc_region: Optional[VoiceRegion] = ..., video_quality_mode: VideoQualityMode = ..., reason: Optional[str] = ..., ) -> Optional[StageChannel]: ... @overload async def edit(self) -> Optional[StageChannel]: ... async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionchanged:: 2.0 The ``topic`` parameter must now be set via :attr:`create_instance`. .. versionchanged:: 2.0 Edits are no longer in-place, the newly edited channel is returned instead. Parameters ---------- name: :class:`str` The new channel's name. position: :class:`int` The new channel's position. sync_permissions: :class:`bool` Whether to sync permissions with the channel's new or pre-existing category. Defaults to ``False``. category: Optional[:class:`CategoryChannel`] The new category for this channel. Can be ``None`` to remove the category. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. overwrites: :class:`Mapping` A :class:`Mapping` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. rtc_region: Optional[:class:`VoiceRegion`] The new region for the stage channel's voice communication. A value of ``None`` indicates automatic voice region detection. video_quality_mode: :class:`VideoQualityMode` The camera video quality for the stage channel's participants. .. versionadded:: 2.0 Raises ------ InvalidArgument If the permission overwrite information is not in proper form. Forbidden You do not have permissions to edit the channel. HTTPException Editing the channel failed. Returns -------- Optional[:class:`.StageChannel`] The newly edited stage channel. If the edit was only positional then ``None`` is returned instead. """ payload = await self._edit(options, reason=reason) if payload is not None: # the payload will always be the proper channel payload return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore class CategoryChannel(discord.abc.GuildChannel, Hashable): """Represents a Discord channel category. These are useful to group channels to logical compartments. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the category's hash. .. describe:: str(x) Returns the category's name. Attributes ----------- name: :class:`str` The category name. guild: :class:`Guild` The guild the category belongs to. id: :class:`int` The category channel ID. position: :class:`int` The position in the category list. This is a number that starts at 0. e.g. the top category is position 0. nsfw: :class:`bool` If the channel is marked as "not safe for work". .. note:: To check if the channel or the guild of that channel are marked as NSFW, consider :meth:`is_nsfw` instead. """ __slots__ = ('name', 'id', 'guild', 'nsfw', '_state', 'position', '_overwrites', 'category_id') def __init__(self, *, state: ConnectionState, guild: Guild, data: CategoryChannelPayload): self._state: ConnectionState = state self.id: int = int(data['id']) self._update(guild, data) def __repr__(self) -> str: return f'<CategoryChannel id={self.id} name={self.name!r} position={self.position} nsfw={self.nsfw}>' def _update(self, guild: Guild, data: CategoryChannelPayload) -> None: self.guild: Guild = guild self.name: str = data['name'] self.category_id: Optional[int] = utils._get_as_snowflake(data, 'parent_id') self.nsfw: bool = data.get('nsfw', False) self.position: int = data['position'] self._fill_overwrites(data) @property def _sorting_bucket(self) -> int: return ChannelType.category.value @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.category def is_nsfw(self) -> bool: """:class:`bool`: Checks if the category is NSFW.""" return self.nsfw @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> CategoryChannel: return await self._clone_impl({'nsfw': self.nsfw}, name=name, reason=reason) @overload async def edit( self, *, name: str = ..., position: int = ..., nsfw: bool = ..., overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = ..., reason: Optional[str] = ..., ) -> Optional[CategoryChannel]: ... @overload async def edit(self) -> Optional[CategoryChannel]: ... async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionchanged:: 1.3 The ``overwrites`` keyword-only parameter was added. .. versionchanged:: 2.0 Edits are no longer in-place, the newly edited channel is returned instead. Parameters ---------- name: :class:`str` The new category's name. position: :class:`int` The new category's position. nsfw: :class:`bool` To mark the category as NSFW or not. reason: Optional[:class:`str`] The reason for editing this category. Shows up on the audit log. overwrites: :class:`Mapping` A :class:`Mapping` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. Raises ------ InvalidArgument If position is less than 0 or greater than the number of categories. Forbidden You do not have permissions to edit the category. HTTPException Editing the category failed. Returns -------- Optional[:class:`.CategoryChannel`] The newly edited category channel. If the edit was only positional then ``None`` is returned instead. """ payload = await self._edit(options, reason=reason) if payload is not None: # the payload will always be the proper channel payload return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore @utils.copy_doc(discord.abc.GuildChannel.move) async def move(self, **kwargs): kwargs.pop('category', None) await super().move(**kwargs) @property def channels(self) -> List[GuildChannelType]: """List[:class:`abc.GuildChannel`]: Returns the channels that are under this category. These are sorted by the official Discord UI, which places voice channels below the text channels. """ def comparator(channel): return (not isinstance(channel, TextChannel), channel.position) ret = [c for c in self.guild.channels if c.category_id == self.id] ret.sort(key=comparator) return ret @property def text_channels(self) -> List[TextChannel]: """List[:class:`TextChannel`]: Returns the text channels that are under this category.""" ret = [c for c in self.guild.channels if c.category_id == self.id and isinstance(c, TextChannel)] ret.sort(key=lambda c: (c.position, c.id)) return ret @property def voice_channels(self) -> List[VoiceChannel]: """List[:class:`VoiceChannel`]: Returns the voice channels that are under this category.""" ret = [c for c in self.guild.channels if c.category_id == self.id and isinstance(c, VoiceChannel)] ret.sort(key=lambda c: (c.position, c.id)) return ret @property def stage_channels(self) -> List[StageChannel]: """List[:class:`StageChannel`]: Returns the stage channels that are under this category. .. versionadded:: 1.7 """ ret = [c for c in self.guild.channels if c.category_id == self.id and isinstance(c, StageChannel)] ret.sort(key=lambda c: (c.position, c.id)) return ret async def create_text_channel(self, name: str, **options: Any) -> TextChannel: """|coro| A shortcut method to :meth:`Guild.create_text_channel` to create a :class:`TextChannel` in the category. Returns ------- :class:`TextChannel` The channel that was just created. """ return await self.guild.create_text_channel(name, category=self, **options) async def create_voice_channel(self, name: str, **options: Any) -> VoiceChannel: """|coro| A shortcut method to :meth:`Guild.create_voice_channel` to create a :class:`VoiceChannel` in the category. Returns ------- :class:`VoiceChannel` The channel that was just created. """ return await self.guild.create_voice_channel(name, category=self, **options) async def create_stage_channel(self, name: str, **options: Any) -> StageChannel: """|coro| A shortcut method to :meth:`Guild.create_stage_channel` to create a :class:`StageChannel` in the category. .. versionadded:: 1.7 Returns ------- :class:`StageChannel` The channel that was just created. """ return await self.guild.create_stage_channel(name, category=self, **options) class StoreChannel(discord.abc.GuildChannel, Hashable): """Represents a Discord guild store channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns the channel's name. Attributes ----------- name: :class:`str` The channel name. guild: :class:`Guild` The guild the channel belongs to. id: :class:`int` The channel ID. category_id: :class:`int` The category channel ID this channel belongs to. 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. nsfw: :class:`bool` If the channel is marked as "not safe for work". .. note:: To check if the channel or the guild of that channel are marked as NSFW, consider :meth:`is_nsfw` instead. """ __slots__ = ( 'name', 'id', 'guild', '_state', 'nsfw', 'category_id', 'position', '_overwrites', ) def __init__(self, *, state: ConnectionState, guild: Guild, data: StoreChannelPayload): self._state: ConnectionState = state self.id: int = int(data['id']) self._update(guild, data) def __repr__(self) -> str: return f'<StoreChannel id={self.id} name={self.name!r} position={self.position} nsfw={self.nsfw}>' def _update(self, guild: Guild, data: StoreChannelPayload) -> None: self.guild: Guild = guild self.name: str = data['name'] self.category_id: Optional[int] = utils._get_as_snowflake(data, 'parent_id') self.position: int = data['position'] self.nsfw: bool = data.get('nsfw', False) self._fill_overwrites(data) @property def _sorting_bucket(self) -> int: return ChannelType.text.value @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.store @utils.copy_doc(discord.abc.GuildChannel.permissions_for) def permissions_for(self, obj: Union[Member, Role], /) -> Permissions: base = super().permissions_for(obj) # store channels do not have voice related permissions denied = Permissions.voice() base.value &= ~denied.value return base def is_nsfw(self) -> bool: """:class:`bool`: Checks if the channel is NSFW.""" return self.nsfw @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> StoreChannel: return await self._clone_impl({'nsfw': self.nsfw}, name=name, reason=reason) @overload async def edit( self, *, name: str = ..., position: int = ..., nsfw: bool = ..., sync_permissions: bool = ..., category: Optional[CategoryChannel], reason: Optional[str], overwrites: Mapping[Union[Role, Member], PermissionOverwrite], ) -> Optional[StoreChannel]: ... @overload async def edit(self) -> Optional[StoreChannel]: ... async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionchanged:: 2.0 Edits are no longer in-place, the newly edited channel is returned instead. Parameters ---------- name: :class:`str` The new channel name. position: :class:`int` The new channel's position. nsfw: :class:`bool` To mark the channel as NSFW or not. sync_permissions: :class:`bool` Whether to sync permissions with the channel's new or pre-existing category. Defaults to ``False``. category: Optional[:class:`CategoryChannel`] The new category for this channel. Can be ``None`` to remove the category. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. overwrites: :class:`Mapping` A :class:`Mapping` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. .. versionadded:: 1.3 Raises ------ InvalidArgument If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form. Forbidden You do not have permissions to edit the channel. HTTPException Editing the channel failed. Returns -------- Optional[:class:`.StoreChannel`] The newly edited store channel. If the edit was only positional then ``None`` is returned instead. """ payload = await self._edit(options, reason=reason) if payload is not None: # the payload will always be the proper channel payload return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore DMC = TypeVar('DMC', bound='DMChannel') class DMChannel(discord.abc.Messageable, Hashable): """Represents a Discord direct message channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns a string representation of the channel Attributes ---------- recipient: Optional[:class:`User`] The user you are participating with in the direct message channel. If this channel is received through the gateway, the recipient information may not be always available. me: :class:`ClientUser` The user presenting yourself. id: :class:`int` The direct message channel ID. """ __slots__ = ('id', 'recipient', 'me', '_state') def __init__(self, *, me: ClientUser, state: ConnectionState, data: DMChannelPayload): self._state: ConnectionState = state self.recipient: Optional[User] = state.store_user(data['recipients'][0]) self.me: ClientUser = me self.id: int = int(data['id']) async def _get_channel(self): return self def __str__(self) -> str: if self.recipient: return f'Direct Message with {self.recipient}' return 'Direct Message with Unknown User' def __repr__(self) -> str: return f'<DMChannel id={self.id} recipient={self.recipient!r}>' @classmethod def _from_message(cls: Type[DMC], state: ConnectionState, channel_id: int) -> DMC: self: DMC = cls.__new__(cls) self._state = state self.id = channel_id self.recipient = None # state.user won't be None here self.me = state.user # type: ignore return self @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.private @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the direct message channel's creation time in UTC.""" return utils.snowflake_time(self.id) def permissions_for(self, obj: Any = None, /) -> Permissions: """Handles permission resolution for a :class:`User`. This function is there for compatibility with other channel types. Actual direct messages do not really have the concept of permissions. This returns all the Text related permissions set to ``True`` except: - :attr:`~Permissions.send_tts_messages`: You cannot send TTS messages in a DM. - :attr:`~Permissions.manage_messages`: You cannot delete others messages in a DM. Parameters ----------- obj: :class:`User` The user to check permissions for. This parameter is ignored but kept for compatibility with other ``permissions_for`` methods. Returns -------- :class:`Permissions` The resolved permissions. """ base = Permissions.text() base.read_messages = True base.send_tts_messages = False base.manage_messages = False return base 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:: 1.6 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) class GroupChannel(discord.abc.Messageable, Hashable): """Represents a Discord group channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns a string representation of the channel Attributes ---------- recipients: List[:class:`User`] The users you are participating with in the group channel. me: :class:`ClientUser` The user presenting yourself. id: :class:`int` The group channel ID. owner: Optional[:class:`User`] The user that owns the group channel. owner_id: :class:`int` The owner ID that owns the group channel. .. versionadded:: 2.0 name: Optional[:class:`str`] The group channel's name if provided. """ __slots__ = ('id', 'recipients', 'owner_id', 'owner', '_icon', 'name', 'me', '_state') def __init__(self, *, me: ClientUser, state: ConnectionState, data: GroupChannelPayload): self._state: ConnectionState = state self.id: int = int(data['id']) self.me: ClientUser = me self._update_group(data) def _update_group(self, data: GroupChannelPayload) -> None: self.owner_id: Optional[int] = utils._get_as_snowflake(data, 'owner_id') self._icon: Optional[str] = data.get('icon') self.name: Optional[str] = data.get('name') self.recipients: List[User] = [self._state.store_user(u) for u in data.get('recipients', [])] self.owner: Optional[BaseUser] if self.owner_id == self.me.id: self.owner = self.me else: self.owner = utils.find(lambda u: u.id == self.owner_id, self.recipients) async def _get_channel(self): return self def __str__(self) -> str: if self.name: return self.name if len(self.recipients) == 0: return 'Unnamed' return ', '.join(map(lambda x: x.name, self.recipients)) def __repr__(self) -> str: return f'<GroupChannel id={self.id} name={self.name!r}>' @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.group @property def icon(self) -> Optional[Asset]: """Optional[:class:`Asset`]: Returns the channel's icon asset if available.""" if self._icon is None: return None return Asset._from_icon(self._state, self.id, self._icon, path='channel') @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" return utils.snowflake_time(self.id) def permissions_for(self, obj: Snowflake, /) -> Permissions: """Handles permission resolution for a :class:`User`. This function is there for compatibility with other channel types. Actual direct messages do not really have the concept of permissions. This returns all the Text related permissions set to ``True`` except: - :attr:`~Permissions.send_tts_messages`: You cannot send TTS messages in a DM. - :attr:`~Permissions.manage_messages`: You cannot delete others messages in a DM. This also checks the kick_members permission if the user is the owner. Parameters ----------- obj: :class:`~discord.abc.Snowflake` The user to check permissions for. Returns -------- :class:`Permissions` The resolved permissions for the user. """ base = Permissions.text() base.read_messages = True base.send_tts_messages = False base.manage_messages = False base.mention_everyone = True if obj.id == self.owner_id: base.kick_members = True return base async def leave(self) -> None: """|coro| Leave the group. If you are the only one in the group, this deletes it as well. Raises ------- HTTPException Leaving the group failed. """ await self._state.http.leave_group(self.id) class PartialMessageable(discord.abc.Messageable, Hashable): """Represents a partial messageable to aid with working messageable channels when only a channel ID are present. The only way to construct this class is through :meth:`Client.get_partial_messageable`. Note that this class is trimmed down and has no rich attributes. .. versionadded:: 2.0 .. container:: operations .. describe:: x == y Checks if two partial messageables are equal. .. describe:: x != y Checks if two partial messageables are not equal. .. describe:: hash(x) Returns the partial messageable's hash. Attributes ----------- id: :class:`int` The channel ID associated with this partial messageable. type: Optional[:class:`ChannelType`] The channel type associated with this partial messageable, if given. """ def __init__(self, state: ConnectionState, id: int, type: Optional[ChannelType] = None): self._state: ConnectionState = state self._channel: Object = Object(id=id) self.id: int = id self.type: Optional[ChannelType] = type async def _get_channel(self) -> Object: return self._channel 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. 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 _guild_channel_factory(channel_type: int): value = try_enum(ChannelType, channel_type) if value is ChannelType.text: return TextChannel, value elif value is ChannelType.voice: return VoiceChannel, value elif value is ChannelType.category: return CategoryChannel, value elif value is ChannelType.news: return TextChannel, value elif value is ChannelType.store: return StoreChannel, value elif value is ChannelType.stage_voice: return StageChannel, value else: return None, value def _channel_factory(channel_type: int): cls, value = _guild_channel_factory(channel_type) if value is ChannelType.private: return DMChannel, value elif value is ChannelType.group: return GroupChannel, value else: return cls, value 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 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
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/channel.py
channel.py
from __future__ import annotations from typing import Any, List, Optional, TYPE_CHECKING, Union from .utils import snowflake_time, _get_as_snowflake, resolve_invite from .user import BaseUser from .activity import Activity, BaseActivity, Spotify, create_activity from .invite import Invite from .enums import Status, try_enum if TYPE_CHECKING: import datetime from .state import ConnectionState from .types.widget import ( WidgetMember as WidgetMemberPayload, Widget as WidgetPayload, ) __all__ = ( 'WidgetChannel', 'WidgetMember', 'Widget', ) class WidgetChannel: """Represents a "partial" widget channel. .. container:: operations .. describe:: x == y Checks if two partial channels are the same. .. describe:: x != y Checks if two partial channels are not the same. .. describe:: hash(x) Return the partial channel's hash. .. describe:: str(x) Returns the partial channel's name. Attributes ----------- id: :class:`int` The channel's ID. name: :class:`str` The channel's name. position: :class:`int` The channel's position """ __slots__ = ('id', 'name', 'position') def __init__(self, id: int, name: str, position: int) -> None: self.id: int = id self.name: str = name self.position: int = position def __str__(self) -> str: return self.name def __repr__(self) -> str: return f'<WidgetChannel id={self.id} name={self.name!r} position={self.position!r}>' @property def mention(self) -> str: """:class:`str`: The string that allows you to mention the channel.""" return f'<#{self.id}>' @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" return snowflake_time(self.id) class WidgetMember(BaseUser): """Represents a "partial" member of the widget's guild. .. container:: operations .. describe:: x == y Checks if two widget members are the same. .. describe:: x != y Checks if two widget members are not the same. .. describe:: hash(x) Return the widget member's hash. .. describe:: str(x) Returns the widget member's `name#discriminator`. Attributes ----------- id: :class:`int` The member's ID. name: :class:`str` The member's username. discriminator: :class:`str` The member's discriminator. bot: :class:`bool` Whether the member is a bot. status: :class:`Status` The member's status. nick: Optional[:class:`str`] The member's nickname. avatar: Optional[:class:`str`] The member's avatar hash. activity: Optional[Union[:class:`BaseActivity`, :class:`Spotify`]] The member's activity. deafened: Optional[:class:`bool`] Whether the member is currently deafened. muted: Optional[:class:`bool`] Whether the member is currently muted. suppress: Optional[:class:`bool`] Whether the member is currently being suppressed. connected_channel: Optional[:class:`WidgetChannel`] Which channel the member is connected to. """ __slots__ = ('name', 'status', 'nick', 'avatar', 'discriminator', 'id', 'bot', 'activity', 'deafened', 'suppress', 'muted', 'connected_channel') if TYPE_CHECKING: activity: Optional[Union[BaseActivity, Spotify]] def __init__( self, *, state: ConnectionState, data: WidgetMemberPayload, connected_channel: Optional[WidgetChannel] = None ) -> None: super().__init__(state=state, data=data) self.nick: Optional[str] = data.get('nick') self.status: Status = try_enum(Status, data.get('status')) self.deafened: Optional[bool] = data.get('deaf', False) or data.get('self_deaf', False) self.muted: Optional[bool] = data.get('mute', False) or data.get('self_mute', False) self.suppress: Optional[bool] = data.get('suppress', False) try: game = data['game'] except KeyError: activity = None else: activity = create_activity(game) self.activity: Optional[Union[BaseActivity, Spotify]] = activity self.connected_channel: Optional[WidgetChannel] = connected_channel def __repr__(self) -> str: return ( f"<WidgetMember name={self.name!r} discriminator={self.discriminator!r}" f" bot={self.bot} nick={self.nick!r}>" ) @property def display_name(self) -> str: """:class:`str`: Returns the member's display name.""" return self.nick or self.name class Widget: """Represents a :class:`Guild` widget. .. container:: operations .. describe:: x == y Checks if two widgets are the same. .. describe:: x != y Checks if two widgets are not the same. .. describe:: str(x) Returns the widget's JSON URL. Attributes ----------- id: :class:`int` The guild's ID. name: :class:`str` The guild's name. channels: List[:class:`WidgetChannel`] The accessible voice channels in the guild. members: List[:class:`Member`] The online members in the server. Offline members do not appear in the widget. .. note:: Due to a Discord limitation, if this data is available the users will be "anonymized" with linear IDs and discriminator information being incorrect. Likewise, the number of members retrieved is capped. """ __slots__ = ('_state', 'channels', '_invite', 'id', 'members', 'name') def __init__(self, *, state: ConnectionState, data: WidgetPayload) -> None: self._state = state self._invite = data['instant_invite'] self.name: str = data['name'] self.id: int = int(data['id']) self.channels: List[WidgetChannel] = [] for channel in data.get('channels', []): _id = int(channel['id']) self.channels.append(WidgetChannel(id=_id, name=channel['name'], position=channel['position'])) self.members: List[WidgetMember] = [] channels = {channel.id: channel for channel in self.channels} for member in data.get('members', []): connected_channel = _get_as_snowflake(member, 'channel_id') if connected_channel in channels: connected_channel = channels[connected_channel] # type: ignore elif connected_channel: connected_channel = WidgetChannel(id=connected_channel, name='', position=0) self.members.append(WidgetMember(state=self._state, data=member, connected_channel=connected_channel)) # type: ignore def __str__(self) -> str: return self.json_url def __eq__(self, other: Any) -> bool: if isinstance(other, Widget): return self.id == other.id return False def __repr__(self) -> str: return f'<Widget id={self.id} name={self.name!r} invite_url={self.invite_url!r}>' @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the member's creation time in UTC.""" return snowflake_time(self.id) @property def json_url(self) -> str: """:class:`str`: The JSON URL of the widget.""" return f"https://discord.com/api/guilds/{self.id}/widget.json" @property def invite_url(self) -> str: """Optional[:class:`str`]: The invite URL for the guild, if available.""" return self._invite async def fetch_invite(self, *, with_counts: bool = True) -> Invite: """|coro| Retrieves an :class:`Invite` from the widget's invite URL. This is the same as :meth:`Client.fetch_invite`; the invite code is abstracted away. Parameters ----------- with_counts: :class:`bool` Whether to include count information in the invite. This fills the :attr:`Invite.approximate_member_count` and :attr:`Invite.approximate_presence_count` fields. Returns -------- :class:`Invite` The invite from the widget's invite URL. """ invite_id = resolve_invite(self._invite) data = await self._state.http.get_invite(invite_id, with_counts=with_counts) return Invite.from_incomplete(state=self._state, data=data)
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/widget.py
widget.py
from __future__ import annotations import asyncio import logging import signal import sys import traceback from typing import Any, Callable, Coroutine, Dict, Generator, List, Optional, Sequence, TYPE_CHECKING, Tuple, TypeVar, Union import aiohttp from .user import User, ClientUser from .invite import Invite from .template import Template from .widget import Widget from .guild import Guild from .emoji import Emoji from .channel import _threaded_channel_factory, PartialMessageable from .enums import ChannelType from .mentions import AllowedMentions from .errors import * from .enums import Status, VoiceRegion from .flags import ApplicationFlags, Intents from .gateway import * from .activity import ActivityTypes, BaseActivity, create_activity from .voice_client import VoiceClient from .http import HTTPClient from .state import ConnectionState from . import utils from .utils import MISSING from .object import Object from .backoff import ExponentialBackoff from .webhook import Webhook from .iterators import GuildIterator from .appinfo import AppInfo from .ui.view import View from .stage_instance import StageInstance from .threads import Thread from .sticker import GuildSticker, StandardSticker, StickerPack, _sticker_factory if TYPE_CHECKING: from .abc import SnowflakeTime, PrivateChannel, GuildChannel, Snowflake from .channel import DMChannel from .message import Message from .member import Member from .voice_client import VoiceProtocol __all__ = ( 'Client', ) Coro = TypeVar('Coro', bound=Callable[..., Coroutine[Any, Any, Any]]) _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 }) 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() class Client: r"""Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API. A number of options can be passed to the :class:`Client`. Parameters ----------- max_messages: Optional[:class:`int`] The maximum number of messages to store in the internal message cache. This defaults to ``1000``. Passing in ``None`` disables the message cache. .. versionchanged:: 1.3 Allow disabling the message cache and change the default size to ``1000``. loop: Optional[:class:`asyncio.AbstractEventLoop`] The :class:`asyncio.AbstractEventLoop` to use for asynchronous operations. Defaults to ``None``, in which case the default event loop is used via :func:`asyncio.get_event_loop()`. connector: Optional[:class:`aiohttp.BaseConnector`] The connector to use for connection pooling. proxy: Optional[:class:`str`] Proxy URL. proxy_auth: Optional[:class:`aiohttp.BasicAuth`] An object that represents proxy HTTP Basic Authorization. shard_id: Optional[:class:`int`] Integer starting at ``0`` and less than :attr:`.shard_count`. shard_count: Optional[:class:`int`] The total number of shards. application_id: :class:`int` The client's application ID. intents: :class:`Intents` The intents that you want to enable for the session. This is a way of disabling and enabling certain gateway events from triggering and being sent. If not given, defaults to a regularly constructed :class:`Intents` class. .. versionadded:: 1.5 member_cache_flags: :class:`MemberCacheFlags` Allows for finer control over how the library caches members. If not given, defaults to cache as much as possible with the currently selected intents. .. versionadded:: 1.5 chunk_guilds_at_startup: :class:`bool` Indicates if :func:`.on_ready` should be delayed to chunk all guilds at start-up if necessary. This operation is incredibly slow for large amounts of guilds. The default is ``True`` if :attr:`Intents.members` is ``True``. .. versionadded:: 1.5 status: Optional[:class:`.Status`] A status to start your presence with upon logging on to Discord. activity: Optional[:class:`.BaseActivity`] An activity to start your presence with upon logging on to Discord. allowed_mentions: Optional[:class:`AllowedMentions`] Control how the client handles mentions by default on every message sent. .. versionadded:: 1.4 heartbeat_timeout: :class:`float` The maximum numbers of seconds before timing out and restarting the WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if processing the initial packets take too long to the point of disconnecting you. The default timeout is 60 seconds. guild_ready_timeout: :class:`float` The maximum number of seconds to wait for the GUILD_CREATE stream to end before preparing the member cache and firing READY. The default timeout is 2 seconds. .. versionadded:: 1.4 assume_unsync_clock: :class:`bool` Whether to assume the system clock is unsynced. This applies to the ratelimit handling code. If this is set to ``True``, the default, then the library uses the time to reset a rate limit bucket given by Discord. If this is ``False`` then your system clock is used to calculate how long to sleep for. If this is set to ``False`` it is recommended to sync your system clock to Google's NTP server. .. versionadded:: 1.3 enable_debug_events: :class:`bool` Whether to enable events that are useful only for debugging gateway related information. Right now this involves :func:`on_socket_raw_receive` and :func:`on_socket_raw_send`. If this is ``False`` then those events will not be dispatched (due to performance considerations). To enable these events, this must be set to ``True``. Defaults to ``False``. .. versionadded:: 2.0 Attributes ----------- ws The websocket gateway the client is currently connected to. Could be ``None``. loop: :class:`asyncio.AbstractEventLoop` The event loop that the client uses for asynchronous operations. """ def __init__( self, *, loop: Optional[asyncio.AbstractEventLoop] = None, **options: Any, ): # self.ws is set in the connect method self.ws: DiscordWebSocket = None # type: ignore self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() if loop is None else loop self._listeners: Dict[str, List[Tuple[asyncio.Future, Callable[..., bool]]]] = {} self.shard_id: Optional[int] = options.get('shard_id') self.shard_count: Optional[int] = options.get('shard_count') connector: Optional[aiohttp.BaseConnector] = options.pop('connector', None) proxy: Optional[str] = options.pop('proxy', None) proxy_auth: Optional[aiohttp.BasicAuth] = options.pop('proxy_auth', None) unsync_clock: bool = options.pop('assume_unsync_clock', True) self.http: HTTPClient = HTTPClient(connector, proxy=proxy, proxy_auth=proxy_auth, unsync_clock=unsync_clock, loop=self.loop) self._handlers: Dict[str, Callable] = { 'ready': self._handle_ready } self._hooks: Dict[str, Callable] = { 'before_identify': self._call_before_identify_hook } self._enable_debug_events: bool = options.pop('enable_debug_events', False) self._connection: ConnectionState = self._get_state(**options) self._connection.shard_count = self.shard_count self._closed: bool = False self._ready: asyncio.Event = asyncio.Event() self._connection._get_websocket = self._get_websocket self._connection._get_client = lambda: self if VoiceClient.warn_nacl: VoiceClient.warn_nacl = False _log.warning("PyNaCl is not installed, voice will NOT be supported") # internals def _get_websocket(self, guild_id: Optional[int] = None, *, shard_id: Optional[int] = None) -> DiscordWebSocket: return self.ws def _get_state(self, **options: Any) -> ConnectionState: return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, loop=self.loop, **options) def _handle_ready(self) -> None: self._ready.set() @property def latency(self) -> float: """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This could be referred to as the Discord WebSocket protocol latency. """ ws = self.ws return float('nan') if not ws else ws.latency def is_ws_ratelimited(self) -> bool: """:class:`bool`: Whether the websocket is currently rate limited. This can be useful to know when deciding whether you should query members using HTTP or via the gateway. .. versionadded:: 1.6 """ if self.ws: return self.ws.is_ratelimited() return False @property def user(self) -> Optional[ClientUser]: """Optional[:class:`.ClientUser`]: Represents the connected client. ``None`` if not logged in.""" return self._connection.user @property def guilds(self) -> List[Guild]: """List[:class:`.Guild`]: The guilds that the connected client is a member of.""" return self._connection.guilds @property def emojis(self) -> List[Emoji]: """List[:class:`.Emoji`]: The emojis that the connected client has.""" return self._connection.emojis @property def stickers(self) -> List[GuildSticker]: """List[:class:`.GuildSticker`]: The stickers that the connected client has. .. versionadded:: 2.0 """ return self._connection.stickers @property def cached_messages(self) -> Sequence[Message]: """Sequence[:class:`.Message`]: Read-only list of messages the connected client has cached. .. versionadded:: 1.1 """ return utils.SequenceProxy(self._connection._messages or []) @property def private_channels(self) -> List[PrivateChannel]: """List[:class:`.abc.PrivateChannel`]: The private channels that the connected client is participating on. .. note:: This returns only up to 128 most recent private channels due to an internal working on how Discord deals with private channels. """ return self._connection.private_channels @property def voice_clients(self) -> List[VoiceProtocol]: """List[:class:`.VoiceProtocol`]: Represents a list of voice connections. These are usually :class:`.VoiceClient` instances. """ return self._connection.voice_clients @property def application_id(self) -> Optional[int]: """Optional[:class:`int`]: The client's application ID. If this is not passed via ``__init__`` then this is retrieved through the gateway when an event contains the data. Usually after :func:`~discord.on_connect` is called. .. versionadded:: 2.0 """ return self._connection.application_id @property def application_flags(self) -> ApplicationFlags: """:class:`~discord.ApplicationFlags`: The client's application flags. .. versionadded:: 2.0 """ return self._connection.application_flags # type: ignore def is_ready(self) -> bool: """:class:`bool`: Specifies if the client's internal cache is ready for use.""" return self._ready.is_set() async def _run_event(self, coro: Callable[..., Coroutine[Any, Any, Any]], event_name: str, *args: Any, **kwargs: Any) -> None: try: await coro(*args, **kwargs) except asyncio.CancelledError: pass except Exception: try: await self.on_error(event_name, *args, **kwargs) except asyncio.CancelledError: pass def _schedule_event(self, coro: Callable[..., Coroutine[Any, Any, Any]], event_name: str, *args: Any, **kwargs: Any) -> asyncio.Task: wrapped = self._run_event(coro, event_name, *args, **kwargs) # Schedules the task return asyncio.create_task(wrapped, name=f'discord.py: {event_name}') def dispatch(self, event: str, *args: Any, **kwargs: Any) -> None: _log.debug('Dispatching event %s', event) method = 'on_' + event listeners = self._listeners.get(event) if listeners: removed = [] for i, (future, condition) in enumerate(listeners): if future.cancelled(): removed.append(i) continue try: result = condition(*args) except Exception as exc: future.set_exception(exc) removed.append(i) else: if result: if len(args) == 0: future.set_result(None) elif len(args) == 1: future.set_result(args[0]) else: future.set_result(args) removed.append(i) if len(removed) == len(listeners): self._listeners.pop(event) else: for idx in reversed(removed): del listeners[idx] try: coro = getattr(self, method) except AttributeError: pass else: self._schedule_event(coro, method, *args, **kwargs) async def on_error(self, event_method: str, *args: Any, **kwargs: Any) -> None: """|coro| The default error handler provided by the client. By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. Check :func:`~discord.on_error` for more details. """ print(f'Ignoring exception in {event_method}', file=sys.stderr) traceback.print_exc() # hooks async def _call_before_identify_hook(self, shard_id: Optional[int], *, initial: bool = False) -> None: # This hook is an internal hook that actually calls the public one. # It allows the library to have its own hook without stepping on the # toes of those who need to override their own hook. await self.before_identify_hook(shard_id, initial=initial) async def before_identify_hook(self, shard_id: Optional[int], *, initial: bool = False) -> None: """|coro| A hook that is called before IDENTIFYing a session. This is useful if you wish to have more control over the synchronization of multiple IDENTIFYing clients. The default implementation sleeps for 5 seconds. .. versionadded:: 1.4 Parameters ------------ shard_id: :class:`int` The shard ID that requested being IDENTIFY'd initial: :class:`bool` Whether this IDENTIFY is the first initial IDENTIFY. """ if not initial: await asyncio.sleep(5.0) # login state management async def login(self, token: str) -> None: """|coro| Logs in the client with the specified credentials. Parameters ----------- token: :class:`str` The authentication token. Do not prefix this token with anything as the library will do it for you. Raises ------ :exc:`.LoginFailure` The wrong credentials are passed. :exc:`.HTTPException` An unknown HTTP related error occurred, usually when it isn't 200 or the known incorrect credentials passing status code. """ _log.info('logging in using static token') data = await self.http.static_login(token.strip()) self._connection.user = ClientUser(state=self._connection, data=data) async def connect(self, *, reconnect: bool = True) -> None: """|coro| Creates a websocket connection and lets the websocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated. Parameters ----------- reconnect: :class:`bool` If we should attempt reconnecting, either due to internet failure or a specific failure on Discord's part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens). Raises ------- :exc:`.GatewayNotFound` If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage. :exc:`.ConnectionClosed` The websocket connection has been terminated. """ backoff = ExponentialBackoff() ws_params = { 'initial': True, 'shard_id': self.shard_id, } while not self.is_closed(): try: coro = DiscordWebSocket.from_client(self, **ws_params) self.ws = await asyncio.wait_for(coro, timeout=60.0) ws_params['initial'] = False while True: await self.ws.poll_event() except ReconnectWebSocket as e: _log.info('Got a request to %s the websocket.', e.op) self.dispatch('disconnect') ws_params.update(sequence=self.ws.sequence, resume=e.resume, session=self.ws.session_id) continue except (OSError, HTTPException, GatewayNotFound, ConnectionClosed, aiohttp.ClientError, asyncio.TimeoutError) as exc: self.dispatch('disconnect') if not reconnect: await self.close() if isinstance(exc, ConnectionClosed) and exc.code == 1000: # clean close, don't re-raise this return raise if self.is_closed(): return # If we get connection reset by peer then try to RESUME if isinstance(exc, OSError) and exc.errno in (54, 10054): ws_params.update(sequence=self.ws.sequence, initial=False, resume=True, session=self.ws.session_id) continue # We should only get this when an unhandled close code happens, # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc) # sometimes, discord sends us 1000 for unknown reasons so we should reconnect # regardless and rely on is_closed instead if isinstance(exc, ConnectionClosed): if exc.code == 4014: raise PrivilegedIntentsRequired(exc.shard_id) from None if exc.code != 1000: await self.close() raise retry = backoff.delay() _log.exception("Attempting a reconnect in %.2fs", retry) await asyncio.sleep(retry) # Always try to RESUME the connection # If the connection is not RESUME-able then the gateway will invalidate the session. # This is apparently what the official Discord client does. ws_params.update(sequence=self.ws.sequence, resume=True, session=self.ws.session_id) async def close(self) -> None: """|coro| Closes the connection to Discord. """ if self._closed: return self._closed = True for voice in self.voice_clients: try: await voice.disconnect(force=True) except Exception: # if an error happens during disconnects, disregard it. pass if self.ws is not None and self.ws.open: await self.ws.close(code=1000) await self.http.close() self._ready.clear() def clear(self) -> None: """Clears the internal state of the bot. After this, the bot can be considered "re-opened", i.e. :meth:`is_closed` and :meth:`is_ready` both return ``False`` along with the bot's internal cache cleared. """ self._closed = False self._ready.clear() self._connection.clear() self.http.recreate() async def start(self, token: str, *, reconnect: bool = True) -> None: """|coro| A shorthand coroutine for :meth:`login` + :meth:`connect`. Raises ------- TypeError An unexpected keyword argument was received. """ await self.login(token) await self.connect(reconnect=reconnect) def run(self, *args: Any, **kwargs: Any) -> None: """A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then this function should not be used. Use :meth:`start` coroutine or :meth:`connect` + :meth:`login`. Roughly Equivalent to: :: try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(close()) # cancel all tasks lingering finally: loop.close() .. warning:: This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns. """ loop = self.loop try: loop.add_signal_handler(signal.SIGINT, lambda: loop.stop()) loop.add_signal_handler(signal.SIGTERM, lambda: loop.stop()) except NotImplementedError: pass async def runner(): try: await self.start(*args, **kwargs) finally: if not self.is_closed(): await self.close() def stop_loop_on_completion(f): loop.stop() future = asyncio.ensure_future(runner(), loop=loop) future.add_done_callback(stop_loop_on_completion) try: loop.run_forever() except KeyboardInterrupt: _log.info('Received signal to terminate bot and event loop.') finally: future.remove_done_callback(stop_loop_on_completion) _log.info('Cleaning up tasks.') _cleanup_loop(loop) if not future.cancelled(): try: return future.result() except KeyboardInterrupt: # I am unsure why this gets raised here but suppress it anyway return None # properties def is_closed(self) -> bool: """:class:`bool`: Indicates if the websocket connection is closed.""" return self._closed @property def activity(self) -> Optional[ActivityTypes]: """Optional[:class:`.BaseActivity`]: The activity being used upon logging in. """ return create_activity(self._connection._activity) @activity.setter def activity(self, value: Optional[ActivityTypes]) -> None: if value is None: self._connection._activity = None elif isinstance(value, BaseActivity): # ConnectionState._activity is typehinted as ActivityPayload, we're passing Dict[str, Any] self._connection._activity = value.to_dict() # type: ignore else: raise TypeError('activity must derive from BaseActivity.') @property def status(self): """:class:`.Status`: The status being used upon logging on to Discord. .. versionadded: 2.0 """ if self._connection._status in set(state.value for state in Status): return Status(self._connection._status) return Status.online @status.setter def status(self, value): if value is Status.offline: self._connection._status = 'invisible' elif isinstance(value, Status): self._connection._status = str(value) else: raise TypeError('status must derive from Status.') @property def allowed_mentions(self) -> Optional[AllowedMentions]: """Optional[:class:`~discord.AllowedMentions`]: The allowed mention configuration. .. versionadded:: 1.4 """ return self._connection.allowed_mentions @allowed_mentions.setter def allowed_mentions(self, value: Optional[AllowedMentions]) -> None: if value is None or isinstance(value, AllowedMentions): self._connection.allowed_mentions = value else: raise TypeError(f'allowed_mentions must be AllowedMentions not {value.__class__!r}') @property def intents(self) -> Intents: """:class:`~discord.Intents`: The intents configured for this connection. .. versionadded:: 1.5 """ return self._connection.intents # helpers/getters @property def users(self) -> List[User]: """List[:class:`~discord.User`]: Returns a list of all the users the bot can see.""" return list(self._connection._users.values()) def get_channel(self, id: int, /) -> Optional[Union[GuildChannel, Thread, PrivateChannel]]: """Returns a channel or thread with the given ID. Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[Union[:class:`.abc.GuildChannel`, :class:`.Thread`, :class:`.abc.PrivateChannel`]] The returned channel or ``None`` if not found. """ return self._connection.get_channel(id) def get_partial_messageable(self, id: int, *, type: Optional[ChannelType] = None) -> PartialMessageable: """Returns a partial messageable with the given channel ID. This is useful if you have a channel_id but don't want to do an API call to send messages to it. .. versionadded:: 2.0 Parameters ----------- id: :class:`int` The channel ID to create a partial messageable for. type: Optional[:class:`.ChannelType`] The underlying channel type for the partial messageable. Returns -------- :class:`.PartialMessageable` The partial messageable """ return PartialMessageable(state=self._connection, id=id, type=type) def get_stage_instance(self, id: int, /) -> Optional[StageInstance]: """Returns a stage instance with the given stage channel ID. .. versionadded:: 2.0 Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[:class:`.StageInstance`] The returns stage instance of ``None`` if not found. """ from .channel import StageChannel channel = self._connection.get_channel(id) if isinstance(channel, StageChannel): return channel.instance def get_guild(self, id: int, /) -> Optional[Guild]: """Returns a guild with the given ID. Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[:class:`.Guild`] The guild or ``None`` if not found. """ return self._connection._get_guild(id) def get_user(self, id: int, /) -> Optional[User]: """Returns a user with the given ID. Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[:class:`~discord.User`] The user or ``None`` if not found. """ return self._connection.get_user(id) def get_emoji(self, id: int, /) -> Optional[Emoji]: """Returns an emoji with the given ID. Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[:class:`.Emoji`] The custom emoji or ``None`` if not found. """ return self._connection.get_emoji(id) def get_sticker(self, id: int, /) -> Optional[GuildSticker]: """Returns a guild sticker with the given ID. .. versionadded:: 2.0 .. note:: To retrieve standard stickers, use :meth:`.fetch_sticker`. or :meth:`.fetch_premium_sticker_packs`. Returns -------- Optional[:class:`.GuildSticker`] The sticker or ``None`` if not found. """ return self._connection.get_sticker(id) def get_all_channels(self) -> Generator[GuildChannel, None, None]: """A generator that retrieves every :class:`.abc.GuildChannel` the client can 'access'. This is equivalent to: :: for guild in client.guilds: for channel in guild.channels: yield channel .. note:: Just because you receive a :class:`.abc.GuildChannel` does not mean that you can communicate in said channel. :meth:`.abc.GuildChannel.permissions_for` should be used for that. Yields ------ :class:`.abc.GuildChannel` A channel the client can 'access'. """ for guild in self.guilds: yield from guild.channels def get_all_members(self) -> Generator[Member, None, None]: """Returns a generator with every :class:`.Member` the client can see. This is equivalent to: :: for guild in client.guilds: for member in guild.members: yield member Yields ------ :class:`.Member` A member the client can see. """ for guild in self.guilds: yield from guild.members # listeners/waiters async def wait_until_ready(self) -> None: """|coro| Waits until the client's internal cache is all ready. """ await self._ready.wait() def wait_for( self, event: str, *, check: Optional[Callable[..., bool]] = None, timeout: Optional[float] = None, ) -> Any: """|coro| Waits for a WebSocket event to be dispatched. This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way. The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default, it does not timeout. Note that this does propagate the :exc:`asyncio.TimeoutError` for you in case of timeout and is provided for ease of use. In case the event returns multiple arguments, a :class:`tuple` containing those arguments is returned instead. Please check the :ref:`documentation <discord-api-events>` for a list of events and their parameters. This function returns the **first event that meets the requirements**. Examples --------- Waiting for a user reply: :: @client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send(f'Hello {msg.author}!') Waiting for a thumbs up reaction from the message author: :: @client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that \N{THUMBS UP SIGN} reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('\N{THUMBS DOWN SIGN}') else: await channel.send('\N{THUMBS UP SIGN}') Parameters ------------ event: :class:`str` The event name, similar to the :ref:`event reference <discord-api-events>`, but without the ``on_`` prefix, to wait for. check: Optional[Callable[..., :class:`bool`]] A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for. timeout: Optional[:class:`float`] The number of seconds to wait before timing out and raising :exc:`asyncio.TimeoutError`. Raises ------- asyncio.TimeoutError If a timeout is provided and it was reached. Returns -------- Any Returns no arguments, a single argument, or a :class:`tuple` of multiple arguments that mirrors the parameters passed in the :ref:`event reference <discord-api-events>`. """ future = self.loop.create_future() if check is None: def _check(*args): return True check = _check ev = event.lower() try: listeners = self._listeners[ev] except KeyError: listeners = [] self._listeners[ev] = listeners listeners.append((future, check)) return asyncio.wait_for(future, timeout) # event registration def event(self, coro: Coro) -> Coro: """A decorator that registers an event to listen to. You can find more info about the events on the :ref:`documentation below <discord-api-events>`. The events must be a :ref:`coroutine <coroutine>`, if not, :exc:`TypeError` is raised. Example --------- .. code-block:: python3 @client.event async def on_ready(): print('Ready!') Raises -------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('event registered must be a coroutine function') setattr(self, coro.__name__, coro) _log.debug('%s has successfully been registered as an event', coro.__name__) return coro async def change_presence( self, *, activity: Optional[BaseActivity] = None, status: Optional[Status] = None, ): """|coro| Changes the client's presence. Example --------- .. code-block:: python3 game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) .. versionchanged:: 2.0 Removed the ``afk`` keyword-only parameter. Parameters ---------- activity: Optional[:class:`.BaseActivity`] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`.Status`] Indicates what status to change to. If ``None``, then :attr:`.Status.online` is used. Raises ------ :exc:`.InvalidArgument` If the ``activity`` parameter is not the proper type. """ if status is None: status_str = 'online' status = Status.online elif status is Status.offline: status_str = 'invisible' status = Status.offline else: status_str = str(status) await self.ws.change_presence(activity=activity, status=status_str) for guild in self._connection.guilds: me = guild.me if me is None: continue if activity is not None: me.activities = (activity,) else: me.activities = () me.status = status # Guild stuff def fetch_guilds( self, *, limit: Optional[int] = 100, before: SnowflakeTime = None, after: SnowflakeTime = None ) -> GuildIterator: """Retrieves an :class:`.AsyncIterator` that enables receiving your guilds. .. note:: Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`, :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`. .. note:: This method is an API call. For general usage, consider :attr:`guilds` instead. Examples --------- Usage :: async for guild in client.fetch_guilds(limit=150): print(guild.name) Flattening into a list :: guilds = await client.fetch_guilds(limit=150).flatten() # guilds is now a list of Guild... All parameters are optional. Parameters ----------- limit: Optional[:class:`int`] The number of guilds to retrieve. If ``None``, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to ``100``. before: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`] Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. after: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`] Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. Raises ------ :exc:`.HTTPException` Getting the guilds failed. Yields -------- :class:`.Guild` The guild with the guild data parsed. """ return GuildIterator(self, limit=limit, before=before, after=after) async def fetch_template(self, code: Union[Template, str]) -> Template: """|coro| Gets a :class:`.Template` from a discord.new URL or code. Parameters ----------- code: Union[:class:`.Template`, :class:`str`] The Discord Template Code or URL (must be a discord.new URL). Raises ------- :exc:`.NotFound` The template is invalid. :exc:`.HTTPException` Getting the template failed. Returns -------- :class:`.Template` The template from the URL/code. """ code = utils.resolve_template(code) data = await self.http.get_template(code) return Template(data=data, state=self._connection) # type: ignore async def fetch_guild(self, guild_id: int, /) -> Guild: """|coro| Retrieves a :class:`.Guild` from an ID. .. note:: Using this, you will **not** receive :attr:`.Guild.channels`, :attr:`.Guild.members`, :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`. .. note:: This method is an API call. For general usage, consider :meth:`get_guild` instead. Parameters ----------- guild_id: :class:`int` The guild's ID to fetch from. Raises ------ :exc:`.Forbidden` You do not have access to the guild. :exc:`.HTTPException` Getting the guild failed. Returns -------- :class:`.Guild` The guild from the ID. """ data = await self.http.get_guild(guild_id) return Guild(data=data, state=self._connection) async def create_guild( self, *, name: str, region: Union[VoiceRegion, str] = VoiceRegion.us_west, icon: bytes = MISSING, code: str = MISSING, ) -> Guild: """|coro| Creates a :class:`.Guild`. Bot accounts in more than 10 guilds are not allowed to create guilds. Parameters ---------- name: :class:`str` The name of the guild. region: :class:`.VoiceRegion` The region for the voice communication server. Defaults to :attr:`.VoiceRegion.us_west`. icon: Optional[:class:`bytes`] The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit` for more details on what is expected. code: :class:`str` The code for a template to create the guild with. .. versionadded:: 1.4 Raises ------ :exc:`.HTTPException` Guild creation failed. :exc:`.InvalidArgument` Invalid icon image format given. Must be PNG or JPG. Returns ------- :class:`.Guild` The guild created. This is not the same guild that is added to cache. """ if icon is not MISSING: icon_base64 = utils._bytes_to_base64_data(icon) else: icon_base64 = None region_value = str(region) if code: data = await self.http.create_from_template(code, name, region_value, icon_base64) else: data = await self.http.create_guild(name, region_value, icon_base64) return Guild(data=data, state=self._connection) async def fetch_stage_instance(self, channel_id: int, /) -> StageInstance: """|coro| Gets a :class:`.StageInstance` for a stage channel id. .. versionadded:: 2.0 Parameters ----------- channel_id: :class:`int` The stage channel ID. Raises ------- :exc:`.NotFound` The stage instance or channel could not be found. :exc:`.HTTPException` Getting the stage instance failed. Returns -------- :class:`.StageInstance` The stage instance from the stage channel ID. """ data = await self.http.get_stage_instance(channel_id) guild = self.get_guild(int(data['guild_id'])) return StageInstance(guild=guild, state=self._connection, data=data) # type: ignore # Invite management async def fetch_invite(self, url: Union[Invite, str], *, with_counts: bool = True, with_expiration: bool = True) -> Invite: """|coro| Gets an :class:`.Invite` from a discord.gg URL or ID. .. note:: If the invite is for a guild you have not joined, the guild and channel attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` and :class:`.PartialInviteChannel` respectively. Parameters ----------- url: Union[:class:`.Invite`, :class:`str`] The Discord invite ID or URL (must be a discord.gg URL). with_counts: :class:`bool` Whether to include count information in the invite. This fills the :attr:`.Invite.approximate_member_count` and :attr:`.Invite.approximate_presence_count` fields. with_expiration: :class:`bool` Whether to include the expiration date of the invite. This fills the :attr:`.Invite.expires_at` field. .. versionadded:: 2.0 Raises ------- :exc:`.NotFound` The invite has expired or is invalid. :exc:`.HTTPException` Getting the invite failed. Returns -------- :class:`.Invite` The invite from the URL/ID. """ invite_id = utils.resolve_invite(url) data = await self.http.get_invite(invite_id, with_counts=with_counts, with_expiration=with_expiration) return Invite.from_incomplete(state=self._connection, data=data) async def delete_invite(self, invite: Union[Invite, str]) -> None: """|coro| Revokes an :class:`.Invite`, URL, or ID to an invite. You must have the :attr:`~.Permissions.manage_channels` permission in the associated guild to do this. Parameters ---------- invite: Union[:class:`.Invite`, :class:`str`] The invite to revoke. Raises ------- :exc:`.Forbidden` You do not have permissions to revoke invites. :exc:`.NotFound` The invite is invalid or expired. :exc:`.HTTPException` Revoking the invite failed. """ invite_id = utils.resolve_invite(invite) await self.http.delete_invite(invite_id) # Miscellaneous stuff async def fetch_widget(self, guild_id: int, /) -> Widget: """|coro| Gets a :class:`.Widget` from a guild ID. .. note:: The guild must have the widget enabled to get this information. Parameters ----------- guild_id: :class:`int` The ID of the guild. Raises ------- :exc:`.Forbidden` The widget for this guild is disabled. :exc:`.HTTPException` Retrieving the widget failed. Returns -------- :class:`.Widget` The guild's widget. """ data = await self.http.get_widget(guild_id) return Widget(state=self._connection, data=data) async def application_info(self) -> AppInfo: """|coro| Retrieves the bot's application information. Raises ------- :exc:`.HTTPException` Retrieving the information failed somehow. Returns -------- :class:`.AppInfo` The bot's application information. """ data = await self.http.application_info() if 'rpc_origins' not in data: data['rpc_origins'] = None return AppInfo(self._connection, data) async def fetch_user(self, user_id: int, /) -> User: """|coro| Retrieves a :class:`~discord.User` based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do. .. note:: This method is an API call. If you have :attr:`discord.Intents.members` and member cache enabled, consider :meth:`get_user` instead. Parameters ----------- user_id: :class:`int` The user's ID to fetch from. Raises ------- :exc:`.NotFound` A user with this ID does not exist. :exc:`.HTTPException` Fetching the user failed. Returns -------- :class:`~discord.User` The user you requested. """ data = await self.http.get_user(user_id) return User(state=self._connection, data=data) async def fetch_channel(self, channel_id: int, /) -> Union[GuildChannel, PrivateChannel, Thread]: """|coro| Retrieves a :class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`, or :class:`.Thread` with the specified ID. .. note:: This method is an API call. For general usage, consider :meth:`get_channel` instead. .. versionadded:: 1.2 Raises ------- :exc:`.InvalidData` An unknown channel type was received from Discord. :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:`.abc.PrivateChannel`, :class:`.Thread`] The channel from the ID. """ data = await self.http.get_channel(channel_id) factory, ch_type = _threaded_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): # the factory will be a DMChannel or GroupChannel here channel = factory(me=self.user, data=data, state=self._connection) # type: ignore else: # the factory can't be a DMChannel or GroupChannel here guild_id = int(data['guild_id']) # type: ignore guild = self.get_guild(guild_id) or Object(id=guild_id) # GuildChannels expect a Guild, we may be passing an Object channel = factory(guild=guild, state=self._connection, data=data) # type: ignore return channel async def fetch_webhook(self, webhook_id: int, /) -> Webhook: """|coro| Retrieves a :class:`.Webhook` with the specified ID. Raises -------- :exc:`.HTTPException` Retrieving the webhook failed. :exc:`.NotFound` Invalid webhook ID. :exc:`.Forbidden` You do not have permission to fetch this webhook. Returns --------- :class:`.Webhook` The webhook you requested. """ data = await self.http.get_webhook(webhook_id) return Webhook.from_state(data, state=self._connection) async def fetch_sticker(self, sticker_id: int, /) -> Union[StandardSticker, GuildSticker]: """|coro| Retrieves a :class:`.Sticker` with the specified ID. .. versionadded:: 2.0 Raises -------- :exc:`.HTTPException` Retrieving the sticker failed. :exc:`.NotFound` Invalid sticker ID. Returns -------- Union[:class:`.StandardSticker`, :class:`.GuildSticker`] The sticker you requested. """ data = await self.http.get_sticker(sticker_id) cls, _ = _sticker_factory(data['type']) # type: ignore return cls(state=self._connection, data=data) # type: ignore async def fetch_premium_sticker_packs(self) -> List[StickerPack]: """|coro| Retrieves all available premium sticker packs. .. versionadded:: 2.0 Raises ------- :exc:`.HTTPException` Retrieving the sticker packs failed. Returns --------- List[:class:`.StickerPack`] All available premium sticker packs. """ data = await self.http.list_premium_sticker_packs() return [StickerPack(state=self._connection, data=pack) for pack in data['sticker_packs']] async def create_dm(self, user: Snowflake) -> DMChannel: """|coro| Creates a :class:`.DMChannel` with this user. This should be rarely called, as this is done transparently for most people. .. versionadded:: 2.0 Parameters ----------- user: :class:`~discord.abc.Snowflake` The user to create a DM with. Returns ------- :class:`.DMChannel` The channel that was created. """ state = self._connection found = state._get_private_channel_by_user(user.id) if found: return found data = await state.http.start_private_message(user.id) return state.add_dm_channel(data) def add_view(self, view: View, *, message_id: Optional[int] = None) -> None: """Registers a :class:`~discord.ui.View` for persistent listening. This method should be used for when a view is comprised of components that last longer than the lifecycle of the program. .. versionadded:: 2.0 Parameters ------------ view: :class:`discord.ui.View` The view to register for dispatching. message_id: Optional[:class:`int`] The message ID that the view is attached to. This is currently used to refresh the view's state during message update events. If not given then message update events are not propagated for the view. Raises ------- TypeError A view was not passed. ValueError The view is not persistent. A persistent view has no timeout and all their components have an explicitly provided custom_id. """ if not isinstance(view, View): raise TypeError(f'expected an instance of View not {view.__class__!r}') if not view.is_persistent(): raise ValueError('View is not persistent. Items need to have a custom_id set and View must have no timeout') self._connection.store_view(view, message_id) @property def persistent_views(self) -> Sequence[View]: """Sequence[:class:`.View`]: A sequence of persistent views added to the client. .. versionadded:: 2.0 """ return self._connection.persistent_views
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/client.py
client.py
from __future__ import annotations import struct from typing import TYPE_CHECKING, ClassVar, IO, Generator, Tuple, Optional from .errors import DiscordException __all__ = ( 'OggError', 'OggPage', 'OggStream', ) class OggError(DiscordException): """An exception that is thrown for Ogg stream parsing errors.""" pass # https://tools.ietf.org/html/rfc3533 # https://tools.ietf.org/html/rfc7845 class OggPage: _header: ClassVar[struct.Struct] = struct.Struct('<xBQIIIB') if TYPE_CHECKING: flag: int gran_pos: int serial: int pagenum: int crc: int segnum: int def __init__(self, stream: IO[bytes]) -> None: try: header = stream.read(struct.calcsize(self._header.format)) self.flag, self.gran_pos, self.serial, \ self.pagenum, self.crc, self.segnum = self._header.unpack(header) self.segtable: bytes = stream.read(self.segnum) bodylen = sum(struct.unpack('B'*self.segnum, self.segtable)) self.data: bytes = stream.read(bodylen) except Exception: raise OggError('bad data stream') from None def iter_packets(self) -> Generator[Tuple[bytes, bool], None, None]: packetlen = offset = 0 partial = True for seg in self.segtable: if seg == 255: packetlen += 255 partial = True else: packetlen += seg yield self.data[offset:offset+packetlen], True offset += packetlen packetlen = 0 partial = False if partial: yield self.data[offset:], False class OggStream: def __init__(self, stream: IO[bytes]) -> None: self.stream: IO[bytes] = stream def _next_page(self) -> Optional[OggPage]: head = self.stream.read(4) if head == b'OggS': return OggPage(self.stream) elif not head: return None else: raise OggError('invalid header magic') def _iter_pages(self) -> Generator[OggPage, None, None]: page = self._next_page() while page: yield page page = self._next_page() def iter_packets(self) -> Generator[bytes, None, None]: partial = b'' for page in self._iter_pages(): for data, complete in page.iter_packets(): partial += data if complete: yield partial partial = b''
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/oggparse.py
oggparse.py
from __future__ import annotations import datetime from typing import Any, Dict, Optional, TYPE_CHECKING, overload, Type, Tuple from .utils import _get_as_snowflake, parse_time, MISSING from .user import User from .errors import InvalidArgument from .enums import try_enum, ExpireBehaviour __all__ = ( 'IntegrationAccount', 'IntegrationApplication', 'Integration', 'StreamIntegration', 'BotIntegration', ) if TYPE_CHECKING: from .types.integration import ( IntegrationAccount as IntegrationAccountPayload, Integration as IntegrationPayload, StreamIntegration as StreamIntegrationPayload, BotIntegration as BotIntegrationPayload, IntegrationType, IntegrationApplication as IntegrationApplicationPayload, ) from .guild import Guild from .role import Role class IntegrationAccount: """Represents an integration account. .. versionadded:: 1.4 Attributes ----------- id: :class:`str` The account ID. name: :class:`str` The account name. """ __slots__ = ('id', 'name') def __init__(self, data: IntegrationAccountPayload) -> None: self.id: str = data['id'] self.name: str = data['name'] def __repr__(self) -> str: return f'<IntegrationAccount id={self.id} name={self.name!r}>' class Integration: """Represents a guild integration. .. versionadded:: 1.4 Attributes ----------- id: :class:`int` The integration ID. name: :class:`str` The integration name. guild: :class:`Guild` The guild of the integration. type: :class:`str` The integration type (i.e. Twitch). enabled: :class:`bool` Whether the integration is currently enabled. account: :class:`IntegrationAccount` The account linked to this integration. user: :class:`User` The user that added this integration. """ __slots__ = ( 'guild', 'id', '_state', 'type', 'name', 'account', 'user', 'enabled', ) def __init__(self, *, data: IntegrationPayload, guild: Guild) -> None: self.guild = guild self._state = guild._state self._from_data(data) def __repr__(self): return f"<{self.__class__.__name__} id={self.id} name={self.name!r}>" def _from_data(self, data: IntegrationPayload) -> None: self.id: int = int(data['id']) self.type: IntegrationType = data['type'] self.name: str = data['name'] self.account: IntegrationAccount = IntegrationAccount(data['account']) user = data.get('user') self.user = User(state=self._state, data=user) if user else None self.enabled: bool = data['enabled'] async def delete(self, *, reason: Optional[str] = None) -> None: """|coro| Deletes the integration. You must have the :attr:`~Permissions.manage_guild` permission to do this. Parameters ----------- reason: :class:`str` The reason the integration was deleted. Shows up on the audit log. .. versionadded:: 2.0 Raises ------- Forbidden You do not have permission to delete the integration. HTTPException Deleting the integration failed. """ await self._state.http.delete_integration(self.guild.id, self.id, reason=reason) class StreamIntegration(Integration): """Represents a stream integration for Twitch or YouTube. .. versionadded:: 2.0 Attributes ---------- id: :class:`int` The integration ID. name: :class:`str` The integration name. guild: :class:`Guild` The guild of the integration. type: :class:`str` The integration type (i.e. Twitch). enabled: :class:`bool` Whether the integration is currently enabled. syncing: :class:`bool` Where the integration is currently syncing. enable_emoticons: Optional[:class:`bool`] Whether emoticons should be synced for this integration (currently twitch only). expire_behaviour: :class:`ExpireBehaviour` The behaviour of expiring subscribers. Aliased to ``expire_behavior`` as well. expire_grace_period: :class:`int` The grace period (in days) for expiring subscribers. user: :class:`User` The user for the integration. account: :class:`IntegrationAccount` The integration account information. synced_at: :class:`datetime.datetime` An aware UTC datetime representing when the integration was last synced. """ __slots__ = ( 'revoked', 'expire_behaviour', 'expire_grace_period', 'synced_at', '_role_id', 'syncing', 'enable_emoticons', 'subscriber_count', ) def _from_data(self, data: StreamIntegrationPayload) -> None: super()._from_data(data) self.revoked: bool = data['revoked'] self.expire_behaviour: ExpireBehaviour = try_enum(ExpireBehaviour, data['expire_behavior']) self.expire_grace_period: int = data['expire_grace_period'] self.synced_at: datetime.datetime = parse_time(data['synced_at']) self._role_id: Optional[int] = _get_as_snowflake(data, 'role_id') self.syncing: bool = data['syncing'] self.enable_emoticons: bool = data['enable_emoticons'] self.subscriber_count: int = data['subscriber_count'] @property def expire_behavior(self) -> ExpireBehaviour: """:class:`ExpireBehaviour`: An alias for :attr:`expire_behaviour`.""" return self.expire_behaviour @property def role(self) -> Optional[Role]: """Optional[:class:`Role`] The role which the integration uses for subscribers.""" return self.guild.get_role(self._role_id) # type: ignore async def edit( self, *, expire_behaviour: ExpireBehaviour = MISSING, expire_grace_period: int = MISSING, enable_emoticons: bool = MISSING, ) -> None: """|coro| Edits the integration. You must have the :attr:`~Permissions.manage_guild` permission to do this. Parameters ----------- expire_behaviour: :class:`ExpireBehaviour` The behaviour when an integration subscription lapses. Aliased to ``expire_behavior`` as well. expire_grace_period: :class:`int` The period (in days) where the integration will ignore lapsed subscriptions. enable_emoticons: :class:`bool` Where emoticons should be synced for this integration (currently twitch only). Raises ------- Forbidden You do not have permission to edit the integration. HTTPException Editing the guild failed. InvalidArgument ``expire_behaviour`` did not receive a :class:`ExpireBehaviour`. """ payload: Dict[str, Any] = {} if expire_behaviour is not MISSING: if not isinstance(expire_behaviour, ExpireBehaviour): raise InvalidArgument('expire_behaviour field must be of type ExpireBehaviour') payload['expire_behavior'] = expire_behaviour.value if expire_grace_period is not MISSING: payload['expire_grace_period'] = expire_grace_period if enable_emoticons is not MISSING: payload['enable_emoticons'] = enable_emoticons # This endpoint is undocumented. # Unsure if it returns the data or not as a result await self._state.http.edit_integration(self.guild.id, self.id, **payload) async def sync(self) -> None: """|coro| Syncs the integration. You must have the :attr:`~Permissions.manage_guild` permission to do this. Raises ------- Forbidden You do not have permission to sync the integration. HTTPException Syncing the integration failed. """ await self._state.http.sync_integration(self.guild.id, self.id) self.synced_at = datetime.datetime.now(datetime.timezone.utc) class IntegrationApplication: """Represents an application for a bot integration. .. versionadded:: 2.0 Attributes ---------- id: :class:`int` The ID for this application. name: :class:`str` The application's name. icon: Optional[:class:`str`] The application's icon hash. description: :class:`str` The application's description. Can be an empty string. summary: :class:`str` The summary of the application. Can be an empty string. user: Optional[:class:`User`] The bot user on this application. """ __slots__ = ( 'id', 'name', 'icon', 'description', 'summary', 'user', ) def __init__(self, *, data: IntegrationApplicationPayload, state): self.id: int = int(data['id']) self.name: str = data['name'] self.icon: Optional[str] = data['icon'] self.description: str = data['description'] self.summary: str = data['summary'] user = data.get('bot') self.user: Optional[User] = User(state=state, data=user) if user else None class BotIntegration(Integration): """Represents a bot integration on discord. .. versionadded:: 2.0 Attributes ---------- id: :class:`int` The integration ID. name: :class:`str` The integration name. guild: :class:`Guild` The guild of the integration. type: :class:`str` The integration type (i.e. Twitch). enabled: :class:`bool` Whether the integration is currently enabled. user: :class:`User` The user that added this integration. account: :class:`IntegrationAccount` The integration account information. application: :class:`IntegrationApplication` The application tied to this integration. """ __slots__ = ('application',) def _from_data(self, data: BotIntegrationPayload) -> None: super()._from_data(data) self.application = IntegrationApplication(data=data['application'], state=self._state) def _integration_factory(value: str) -> Tuple[Type[Integration], str]: if value == 'discord': return BotIntegration, value elif value in ('twitch', 'youtube'): return StreamIntegration, value else: return Integration, value
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/integrations.py
integrations.py
from __future__ import annotations from typing import Any, Dict, List, Optional, TypeVar, Union, overload, TYPE_CHECKING from .permissions import Permissions from .errors import InvalidArgument from .colour import Colour from .mixins import Hashable from .utils import snowflake_time, _get_as_snowflake, MISSING __all__ = ( 'RoleTags', 'Role', ) if TYPE_CHECKING: import datetime from .types.role import ( Role as RolePayload, RoleTags as RoleTagPayload, ) from .types.guild import RolePositionUpdate from .guild import Guild from .member import Member from .state import ConnectionState class RoleTags: """Represents tags on a role. A role tag is a piece of extra information attached to a managed role that gives it context for the reason the role is managed. While this can be accessed, a useful interface is also provided in the :class:`Role` and :class:`Guild` classes as well. .. versionadded:: 1.6 Attributes ------------ bot_id: Optional[:class:`int`] The bot's user ID that manages this role. integration_id: Optional[:class:`int`] The integration ID that manages the role. """ __slots__ = ( 'bot_id', 'integration_id', '_premium_subscriber', ) def __init__(self, data: RoleTagPayload): self.bot_id: Optional[int] = _get_as_snowflake(data, 'bot_id') self.integration_id: Optional[int] = _get_as_snowflake(data, 'integration_id') # NOTE: The API returns "null" for this if it's valid, which corresponds to None. # This is different from other fields where "null" means "not there". # So in this case, a value of None is the same as True. # Which means we would need a different sentinel. self._premium_subscriber: Optional[Any] = data.get('premium_subscriber', MISSING) def is_bot_managed(self) -> bool: """:class:`bool`: Whether the role is associated with a bot.""" return self.bot_id is not None def is_premium_subscriber(self) -> bool: """:class:`bool`: Whether the role is the premium subscriber, AKA "boost", role for the guild.""" return self._premium_subscriber is None def is_integration(self) -> bool: """:class:`bool`: Whether the role is managed by an integration.""" return self.integration_id is not None def __repr__(self) -> str: return ( f'<RoleTags bot_id={self.bot_id} integration_id={self.integration_id} ' f'premium_subscriber={self.is_premium_subscriber()}>' ) R = TypeVar('R', bound='Role') 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', '_state', ) def __init__(self, *, guild: Guild, state: ConnectionState, data: RolePayload): 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: R, other: R) -> 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: R, other: R) -> bool: r = Role.__lt__(other, self) if r is NotImplemented: return NotImplemented return not r def __gt__(self: R, other: R) -> bool: return Role.__lt__(other, self) def __ge__(self: R, other: R) -> bool: r = Role.__lt__(self, other) if r is NotImplemented: return NotImplemented return not r def _update(self, data: RolePayload): 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.tags: Optional[RoleTags] try: self.tags = RoleTags(data['tags']) except KeyError: self.tags = None 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) @property def permissions(self) -> Permissions: """:class:`Permissions`: Returns the role's permissions.""" return Permissions(self._permissions) @property def colour(self) -> Colour: """:class:`Colour`: Returns the role colour. An alias exists under ``color``.""" return Colour(self._colour) @property def color(self) -> Colour: """:class:`Colour`: Returns the role color. An alias exists under ``colour``.""" return self.colour @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the role's creation time in UTC.""" return snowflake_time(self.id) @property def mention(self) -> str: """:class:`str`: Returns a string that allows you to mention a role.""" return f'<@&{self.id}>' @property 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)] 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, ) -> 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. 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. 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 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)
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/role.py
role.py
from __future__ import annotations import copy import unicodedata from typing import ( Any, ClassVar, Dict, List, NamedTuple, Sequence, Set, Literal, Optional, TYPE_CHECKING, Tuple, Union, overload, ) from . import utils, abc from .role import Role from .member import Member, VoiceState from .emoji import Emoji from .errors import InvalidData from .permissions import PermissionOverwrite from .colour import Colour from .errors import InvalidArgument, ClientException from .channel import * from .channel import _guild_channel_factory from .channel import _threaded_guild_channel_factory from .enums import ( AuditLogAction, VideoQualityMode, VoiceRegion, ChannelType, try_enum, VerificationLevel, ContentFilter, NotificationLevel, NSFWLevel, ) from .mixins import Hashable from .user import User from .invite import Invite from .iterators import AuditLogIterator, MemberIterator from .widget import Widget from .asset import Asset from .flags import SystemChannelFlags from .integrations import Integration, _integration_factory from .stage_instance import StageInstance from .threads import Thread, ThreadMember from .sticker import GuildSticker from .file import File __all__ = ( 'Guild', ) MISSING = utils.MISSING if TYPE_CHECKING: from .abc import Snowflake, SnowflakeTime from .types.guild import Ban as BanPayload, Guild as GuildPayload, MFALevel, GuildFeature from .types.threads import ( Thread as ThreadPayload, ) from .types.voice import GuildVoiceState from .permissions import Permissions from .channel import VoiceChannel, StageChannel, TextChannel, CategoryChannel, StoreChannel from .template import Template from .webhook import Webhook from .state import ConnectionState from .voice_client import VoiceProtocol import datetime VocalGuildChannel = Union[VoiceChannel, StageChannel] GuildChannel = Union[VoiceChannel, StageChannel, TextChannel, CategoryChannel, StoreChannel] ByCategoryItem = Tuple[Optional[CategoryChannel], List[GuildChannel]] class BanEntry(NamedTuple): reason: Optional[str] user: User class _GuildLimit(NamedTuple): emoji: int stickers: int bitrate: float filesize: int 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_ICON``: Guild can upload an animated icon. - ``BANNER``: Guild can upload and use a banner. (i.e. :attr:`.banner`) - ``COMMERCE``: Guild can sell things using store channels. - ``COMMUNITY``: Guild is a community server. - ``DISCOVERABLE``: Guild shows up in Server Discovery. - ``FEATURABLE``: Guild is able to be featured in Server Discovery. - ``INVITE_SPLASH``: Guild's invite page can have a special splash. - ``MEMBER_VERIFICATION_GATE_ENABLED``: Guild has Membership Screening enabled. - ``MONETIZATION_ENABLED``: Guild has enabled monetization. - ``MORE_EMOJI``: Guild has increased custom emoji slots. - ``MORE_STICKERS``: Guild has increased custom sticker slots. - ``NEWS``: Guild can create news channels. - ``PARTNERED``: Guild is a partnered server. - ``PREVIEW_ENABLED``: Guild can be viewed before being accepted via Membership Screening. - ``PRIVATE_THREADS``: Guild has access to create private threads. - ``SEVEN_DAY_THREAD_ARCHIVE``: Guild has access to the seven day archive time for threads. - ``THREE_DAY_THREAD_ARCHIVE``: Guild has access to the three day archive time for threads. - ``TICKETED_EVENTS_ENABLED``: Guild has enabled ticketed events. - ``VANITY_URL``: Guild can have a vanity invite URL (e.g. discord.gg/discord-api). - ``VERIFIED``: Guild is a verified server. - ``VIP_REGIONS``: Guild has VIP voice regions. - ``WELCOME_SCREEN_ENABLED``: Guild has enabled the welcome screen. premium_tier: :class:`int` The premium tier for this guild. Corresponds to "Nitro Server" 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 """ __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', '_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', ) _PREMIUM_GUILD_LIMITS: ClassVar[Dict[Optional[int], _GuildLimit]] = { None: _GuildLimit(emoji=50, stickers=0, bitrate=96e3, filesize=8388608), 0: _GuildLimit(emoji=50, stickers=0, bitrate=96e3, filesize=8388608), 1: _GuildLimit(emoji=100, stickers=15, bitrate=128e3, filesize=8388608), 2: _GuildLimit(emoji=150, stickers=30, bitrate=256e3, filesize=52428800), 3: _GuildLimit(emoji=250, stickers=60, bitrate=384e3, filesize=104857600), } def __init__(self, *, data: GuildPayload, state: ConnectionState): self._channels: Dict[int, GuildChannel] = {} self._members: Dict[int, Member] = {} self._voice_states: Dict[int, VoiceState] = {} self._threads: Dict[int, Thread] = {} 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 __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) except KeyError: # if we're here then we're getting added into the cache after = VoiceState(data=data, channel=channel) before = VoiceState(data=data, channel=None) 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(map(lambda d: state.store_emoji(self, d), guild.get('emojis', []))) self.stickers: Tuple[GuildSticker, ...] = tuple( map(lambda d: state.store_sticker(self, d), 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.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._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) 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'])) # TODO: refactor/remove? def _sync(self, data: GuildPayload) -> None: try: self._large = data['large'] except KeyError: pass empty_tuple = 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, ch_type = _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)) @property def channels(self) -> List[GuildChannel]: """List[:class:`abc.GuildChannel`]: A list of channels that belongs to this guild.""" return list(self._channels.values()) @property 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()) @property 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 @property def voice_channels(self) -> List[VoiceChannel]: """List[:class:`VoiceChannel`]: A list of voice channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, VoiceChannel)] r.sort(key=lambda c: (c.position, c.id)) return r @property def stage_channels(self) -> List[StageChannel]: """List[:class:`StageChannel`]: A list of stage channels that belongs 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 @property 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 # The self member is *always* cached return self.get_member(self_id) # type: ignore @property 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) @property def text_channels(self) -> List[TextChannel]: """List[:class:`TextChannel`]: A list of text channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, TextChannel)] r.sort(key=lambda c: (c.position, c.id)) return r @property def categories(self) -> List[CategoryChannel]: """List[:class:`CategoryChannel`]: A list of categories that belongs 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 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 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) @property 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 @property def system_channel_flags(self) -> SystemChannelFlags: """:class:`SystemChannelFlags`: Returns the guild's system channel settings.""" return SystemChannelFlags._from_value(self._system_channel_flags) @property 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 @property 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 @property 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) @property 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 0 return max(more_stickers, self._PREMIUM_GUILD_LIMITS[self.premium_tier].stickers) @property 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) @property 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 @property def members(self) -> List[Member]: """List[:class:`Member`]: A list of members that belong to this guild.""" return list(self._members.values()) 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) @property 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] @property 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) @property 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 @property 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 @property 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 @property 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) @property def owner(self) -> Optional[Member]: """Optional[:class:`Member`]: The member that owns the guild.""" return self.get_member(self.owner_id) # type: ignore @property 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) @property 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') @property 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') @property 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') @property def member_count(self) -> int: """:class:`int`: Returns the true member count regardless of it being loaded fully or not. .. warning:: Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires :attr:`Intents.members` to be specified. """ return self._member_count @property 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) @property 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 @property 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 m.nick == name or m.name == 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, ) -> 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: discord.PermissionOverwrite(read_messages=False), guild.me: discord.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 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) # 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) # 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, 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. 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 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) # 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) # 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[bytes] = MISSING, banner: Optional[bytes] = MISSING, splash: Optional[bytes] = MISSING, discovery_splash: Optional[bytes] = 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, ) -> 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. 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: :class:`bytes` A :term:`py:bytes-like object` 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: :class:`bytes` A :term:`py:bytes-like object` representing the banner. Could be ``None`` to denote removal of the banner. This is only available to guilds that contain ``BANNER`` in :attr:`Guild.features`. splash: :class:`bytes` A :term:`py:bytes-like object` representing the invite splash. Only PNG/JPEG supported. Could be ``None`` to denote removing the splash. This is only available to guilds that contain ``INVITE_SPLASH`` in :attr:`Guild.features`. discovery_splash: :class:`bytes` A :term:`py:bytes-like object` representing the discovery splash. Only PNG/JPEG supported. Could be ``None`` to denote removing the splash. This is only available to guilds that contain ``DISCOVERABLE`` in :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. 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: if icon is None: fields['icon'] = icon else: fields['icon'] = utils._bytes_to_base64_data(icon) if banner is not MISSING: if banner is None: fields['banner'] = banner else: fields['banner'] = utils._bytes_to_base64_data(banner) if splash is not MISSING: if splash is None: fields['splash'] = splash else: fields['splash'] = utils._bytes_to_base64_data(splash) if discovery_splash is not MISSING: if discovery_splash is None: fields['discovery_splash'] = discovery_splash else: fields['discovery_splash'] = utils._bytes_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 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 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, ch_type = _guild_channel_factory(d['type']) if factory is None: raise InvalidData('Unknown channel type {type} for channel ID {id}.'.format_map(d)) channel = factory(guild=self, state=self._state, data=d) return channel 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: 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') 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 async def bans(self) -> List[BanEntry]: """|coro| Retrieves all the users that are banned from the guild as a :class:`list` of :class:`BanEntry`. You must have the :attr:`~Permissions.ban_members` permission to get this information. Raises ------- Forbidden You do not have proper permissions to get the information. HTTPException An error occurred while fetching the information. Returns -------- List[:class:`BanEntry`] A list of :class:`BanEntry` objects. """ data: List[BanPayload] = await self._state.http.get_bans(self.id) return [BanEntry(user=User(state=self._state, data=e['user']), reason=e['reason']) for e in data] 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.') if roles: role_ids = [str(role.id) for role in roles] else: role_ids = [] 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) -> 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.') if roles: role_ids = [str(role.id) for role in roles] else: role_ids = [] 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. """ 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 = {'name': name} 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: str, 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']) if factory is None: raise InvalidData('Unknown integration type {type!r} for integration ID {id}'.format_map(d)) 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. """ payload = { 'name': name, } if description: payload['description'] = description try: emoji = unicodedata.name(emoji) except TypeError: pass else: emoji = emoji.replace(' ', '_') payload['tags'] = emoji data = await self._state.http.create_guild_sticker(self.id, payload, file, 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: bytes, 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. Parameters ----------- name: :class:`str` The emoji name. Must be at least 2 characters. image: :class:`bytes` The :term:`py:bytes-like object` 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 = utils._bytes_to_base64_data(image) if roles: role_ids = [role.id for role in roles] else: role_ids = [] data = await self._state.http.create_custom_emoji(self.id, name, img, 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) -> 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. .. versionadded:: 1.3 Raises ------- HTTPException Retrieving the roles failed. Returns ------- List[:class:`Role`] All roles in the guild. """ data = await self._state.http.get_roles(self.id) return [Role(guild=self, state=self._state, data=d) for d in data] @overload async def create_role( self, *, reason: Optional[str] = ..., name: str = ..., permissions: Permissions = ..., colour: Union[Colour, int] = ..., hoist: bool = ..., mentionable: bool = ..., ) -> Role: ... @overload async def create_role( self, *, reason: Optional[str] = ..., name: str = ..., permissions: Permissions = ..., color: Union[Colour, int] = ..., hoist: bool = ..., mentionable: bool = ..., ) -> 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, 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. 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``. 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 data = await self._state.http.create_role(self.id, reason=reason, **fields) role = Role(guild=self, data=data, state=self._state) # TODO: add to cache return role 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[Dict[str, Any]] = [] for role, position in positions.items(): payload = {'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_days: Literal[0, 1, 2, 3, 4, 5, 6, 7] = 1, ) -> 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. Parameters ----------- user: :class:`abc.Snowflake` The user to ban from their guild. delete_message_days: :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. reason: Optional[:class:`str`] The reason the user got banned. Raises ------- Forbidden You do not have the proper permissions to ban. HTTPException Banning failed. """ await self._state.http.ban(user.id, self.id, delete_message_days, 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: int = 100, before: Optional[SnowflakeTime] = None, after: Optional[SnowflakeTime] = None, oldest_first: Optional[bool] = None, user: Snowflake = None, action: 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=discord.AuditLogAction.ban): print(f'{entry.user} banned {entry.target}') Getting entries made by a specific user: :: entries = await guild.audit_logs(limit=None, user=guild.me).flatten() await channel.send(f'I made {len(entries)} moderation actions.') Parameters ----------- limit: Optional[:class:`int`] The number of entries to retrieve. If ``None`` retrieve all entries. before: 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: 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: :class:`bool` If set to ``True``, return entries in oldest->newest order. Defaults to ``True`` if ``after`` is specified, otherwise ``False``. user: :class:`abc.Snowflake` The moderator to filter entries from. action: :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. """ if user is not None: user_id = user.id else: user_id = None if action: action = action.value 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:`~discord.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) -> None: """|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. """ if not self._state._intents.members: raise ClientException('Intents.members must be enabled to use this.') if not self._state.is_guild_evicted(self): return await self._state.chunk_guild(self, cache=cache) 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 query is None: 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 ): """|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)
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/guild.py
guild.py
from __future__ import annotations from typing import Dict, List, Optional, TYPE_CHECKING, Any, Tuple, Union if TYPE_CHECKING: from aiohttp import ClientResponse, ClientWebSocketResponse try: from requests import Response _ResponseType = Union[ClientResponse, Response] except ModuleNotFoundError: _ResponseType = ClientResponse from .interactions import Interaction __all__ = ( 'DiscordException', 'ClientException', 'NoMoreItems', 'GatewayNotFound', 'HTTPException', 'Forbidden', 'NotFound', 'DiscordServerError', 'InvalidData', 'InvalidArgument', 'LoginFailure', 'ConnectionClosed', 'PrivilegedIntentsRequired', 'InteractionResponded', ) class DiscordException(Exception): """Base exception class for discord.py Ideally speaking, this could be caught to handle any exceptions raised from this library. """ pass class ClientException(DiscordException): """Exception that's raised when an operation in the :class:`Client` fails. These are usually for exceptions that happened due to user input. """ pass class NoMoreItems(DiscordException): """Exception that is raised when an async iteration operation has no more items.""" pass class GatewayNotFound(DiscordException): """An exception that is raised when the gateway for Discord could not be found""" def __init__(self): message = 'The gateway to connect to discord was not found.' super().__init__(message) 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) class HTTPException(DiscordException): """Exception that's raised when an HTTP request operation fails. Attributes ------------ response: :class:`aiohttp.ClientResponse` The response of the failed HTTP request. This is an instance of :class:`aiohttp.ClientResponse`. In some cases this could also be a :class:`requests.Response`. text: :class:`str` The text of the error. Could be an empty string. status: :class:`int` The status code of the HTTP request. code: :class:`int` The Discord specific error code for the failure. """ def __init__(self, response: _ResponseType, message: Optional[Union[str, Dict[str, Any]]]): self.response: _ResponseType = response self.status: int = response.status # type: ignore self.code: int self.text: str if isinstance(message, dict): self.code = message.get('code', 0) base = message.get('message', '') errors = message.get('errors') if errors: errors = _flatten_error_dict(errors) helpful = '\n'.join('In %s: %s' % t for t in errors.items()) self.text = base + '\n' + helpful else: self.text = base else: self.text = message or '' self.code = 0 fmt = '{0.status} {0.reason} (error code: {1})' if len(self.text): fmt += ': {2}' super().__init__(fmt.format(self.response, self.code, self.text)) class Forbidden(HTTPException): """Exception that's raised for when status code 403 occurs. Subclass of :exc:`HTTPException` """ pass class NotFound(HTTPException): """Exception that's raised for when status code 404 occurs. Subclass of :exc:`HTTPException` """ pass class DiscordServerError(HTTPException): """Exception that's raised for when a 500 range status code occurs. Subclass of :exc:`HTTPException`. .. versionadded:: 1.5 """ pass class InvalidData(ClientException): """Exception that's raised when the library encounters unknown or invalid data from Discord. """ pass 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`. """ pass class LoginFailure(ClientException): """Exception that's raised when the :meth:`Client.login` function fails to log you in from improper credentials or some other misc. failure. """ pass class ConnectionClosed(ClientException): """Exception that's raised when the gateway connection is closed for reasons that could not be handled internally. Attributes ----------- code: :class:`int` The close code of the websocket. reason: :class:`str` The reason provided for the closure. shard_id: Optional[:class:`int`] The shard ID that got closed if applicable. """ def __init__(self, socket: ClientWebSocketResponse, *, shard_id: Optional[int], code: Optional[int] = None): # This exception is just the same exception except # reconfigured to subclass ClientException for users self.code: int = code or socket.close_code or -1 # aiohttp doesn't seem to consistently provide close reason self.reason: str = '' self.shard_id: Optional[int] = shard_id super().__init__(f'Shard ID {self.shard_id} WebSocket closed with {self.code}') class PrivilegedIntentsRequired(ClientException): """Exception that's raised when the gateway is requesting privileged intents but they're not ticked in the developer page yet. Go to https://discord.com/developers/applications/ and enable the intents that are required. Currently these are as follows: - :attr:`Intents.members` - :attr:`Intents.presences` Attributes ----------- shard_id: Optional[:class:`int`] The shard ID that got closed if applicable. """ def __init__(self, shard_id: Optional[int]): self.shard_id: Optional[int] = shard_id msg = ( 'Shard ID %s is requesting privileged intents that have not been explicitly enabled in the ' 'developer portal. It is recommended to go to https://discord.com/developers/applications/ ' 'and explicitly enable the privileged intents within your application\'s page. If this is not ' 'possible, then consider disabling the privileged intents instead.' ) super().__init__(msg % shard_id) class InteractionResponded(ClientException): """Exception that's raised when sending another interaction response using :class:`InteractionResponse` when one has already been done before. An interaction can only respond once. .. versionadded:: 2.0 Attributes ----------- interaction: :class:`Interaction` The interaction that's already been responded to. """ def __init__(self, interaction: Interaction): self.interaction: Interaction = interaction super().__init__('This interaction has already been responded to before')
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/errors.py
errors.py
from __future__ import annotations import inspect from collections import defaultdict import discord, discord.channel, discord.http, discord.state from discord.ext import commands from discord.utils import MISSING from typing import Coroutine, TypeVar, Union, get_args, get_origin, overload, Generic, TYPE_CHECKING BotT = TypeVar("BotT", bound='Bot') CtxT = TypeVar("CtxT", bound='Context') CogT = TypeVar("CogT", bound='ApplicationCog') NumT = Union[int, float] __all__ = ['describe', 'SlashCommand', 'ApplicationCog', 'Range', 'Context', 'Bot', 'slash_command', 'message_command', 'user_command'] if TYPE_CHECKING: from typing import Any, Awaitable, Callable, ClassVar from typing_extensions import Concatenate, ParamSpec CmdP = ParamSpec("CmdP") CmdT = Callable[Concatenate[CogT, CtxT, CmdP], Awaitable[Any]] MsgCmdT = Callable[[CogT, CtxT, discord.Message], Awaitable[Any]] UsrCmdT = Callable[[CogT, CtxT, discord.Member], Awaitable[Any]] CtxMnT = Union[MsgCmdT, UsrCmdT] RngT = TypeVar("RngT", bound='Range') command_type_map: dict[type[Any], int] = { str: 3, int: 4, bool: 5, discord.User: 6, discord.Member: 6, discord.TextChannel: 7, discord.VoiceChannel: 7, discord.CategoryChannel: 7, discord.Role: 8, float: 10 } channel_filter: dict[type[discord.abc.GuildChannel], int] = { discord.TextChannel: 0, discord.VoiceChannel: 2, discord.CategoryChannel: 4 } def describe(**kwargs): """ Sets the description for the specified parameters of the slash command. Sample usage: ```python @zarena.slash_command() @describe(channel="The channel to ping") async def mention(self, ctx: zarena.Context, channel: discord.TextChannel): await ctx.send(f'{channel.mention}') ``` If this decorator is not used, parameter descriptions will be set to "No description provided." instead.""" def _inner(cmd): func = cmd.func if isinstance(cmd, SlashCommand) else cmd for name, desc in kwargs.items(): try: func._param_desc_[name] = desc except AttributeError: func._param_desc_ = {name: desc} return cmd return _inner def slash_command(**kwargs) -> Callable[[CmdT], SlashCommand]: """ Defines a function as a slash-type application command. Parameters: - name: ``str`` - - The display name of the command. If unspecified, will use the functions name. - guild_id: ``Optional[int]`` - - The guild ID this command will belong to. If unspecified, the command will be uploaded globally. - description: ``str`` - - The description of the command. If unspecified, will use the functions docstring, or "No description provided" otherwise. """ def _inner(func: CmdT) -> SlashCommand: return SlashCommand(func, **kwargs) return _inner def message_command(**kwargs) -> Callable[[MsgCmdT], MessageCommand]: """ Defines a function as a message-type application command. Parameters: - name: ``str`` - - The display name of the command. If unspecified, will use the functions name. - guild_id: ``Optional[int]`` - - The guild ID this command will belong to. If unspecified, the command will be uploaded globally. """ def _inner(func: MsgCmdT) -> MessageCommand: return MessageCommand(func, **kwargs) return _inner def user_command(**kwargs) -> Callable[[UsrCmdT], UserCommand]: """ Defines a function as a user-type application command. Parameters: - name: ``str`` - - The display name of the command. If unspecified, will use the functions name. - guild_id: ``Optional[int]`` - - The guild ID this command will belong to. If unspecified, the command will be uploaded globally. """ def _inner(func: UsrCmdT) -> UserCommand: return UserCommand(func, **kwargs) return _inner class _RangeMeta(type): @overload def __getitem__(cls: type[RngT], max: int) -> type[int]: ... @overload def __getitem__(cls: type[RngT], max: tuple[int, int]) -> type[int]: ... @overload def __getitem__(cls: type[RngT], max: float) -> type[float]: ... @overload def __getitem__(cls: type[RngT], max: tuple[float, float]) -> type[float]: ... def __getitem__(cls, max): if isinstance(max, tuple): return cls(*max) return cls(None, max) class Range(metaclass=_RangeMeta): """ Defines a minimum and maximum value for float or int values. The minimum value is optional. ```python async def number(self, ctx, num: zarena.Range[0, 10], other_num: zarena.Range[10]): ... ```""" def __init__(self, min: NumT | None, max: NumT): if min is not None and min >= max: raise ValueError("`min` value must be lower than `max`") self.min = min self.max = max class Bot(commands.Bot): async def start(self, token: str, *, reconnect: bool = True) -> None: await self.login(token) app_info = await self.application_info() self._connection.application_id = app_info.id await self.sync_commands() await self.connect(reconnect=reconnect) def get_application_command(self, name: str) -> Command | None: """ Gets and returns an application command by the given name. Parameters: - name: ``str`` - - The name of the command. Returns: - [Command](#deco-slash_commandkwargs) - - The relevant command object - ``None`` - - No command by that name was found. """ for c in self.cogs.values(): if isinstance(c, ApplicationCog): c = c._commands.get(name) if c: return c async def delete_all_commands(self, guild_id: int | None = None): """ Deletes all commands on the specified guild, or all global commands if no guild id was given. Parameters: - guild_id: ``Optional[str]`` - - The guild ID to delete from, or ``None`` to delete global commands. """ path = f'/applications/{self.application_id}' if guild_id is not None: path += f'/guilds/{guild_id}' path += '/commands' route = discord.http.Route("GET", path) data = await self.http.request(route) for cmd in data: snow = cmd['id'] await self.delete_command(snow, guild_id=guild_id) async def delete_command(self, id: int, *, guild_id: int | None = None): """ Deletes a command with the specified ID. The ID is a snowflake, not the name of the command. Parameters: - id: ``int`` - - The ID of the command to delete. - guild_id: ``Optional[str]`` - - The guild ID to delete from, or ``None`` to delete a global command. """ route = discord.http.Route('DELETE', f'/applications/{self.application_id}{f"/guilds/{guild_id}" if guild_id else ""}/commands/{id}') await self.http.request(route) async def sync_commands(self) -> None: """ Uploads all commands from cogs found and syncs them with discord. Global commands will take up to an hour to update. Guild specific commands will update immediately. """ if not self.application_id: raise RuntimeError("sync_commands must be called after `run`, `start` or `login`") for cog in self.cogs.values(): if not isinstance(cog, ApplicationCog): continue for cmd in cog._commands.values(): cmd.cog = cog route = f"/applications/{self.application_id}" if cmd.guild_id: route += f"/guilds/{cmd.guild_id}" route += '/commands' body = cmd._build_command_payload() route = discord.http.Route('POST', route) await self.http.request(route, json=body) class Context(Generic[BotT, CogT]): """ The command interaction context. Attributes - bot: [``zarena.Bot``](#class-botcommand_prefix-help_commanddefault-help-command-descriptionnone-options) - - Your bot object. - command: Union[[SlashCommand](#deco-slash_commandkwargs), [UserCommand](#deco-user_commandkwargs), [MessageCommand](deco-message_commandkwargs)] - - The command used with this interaction. - interaction: [``discord.Interaction``](https://discordpy.readthedocs.io/en/master/api.html#discord.Interaction) - - The interaction tied to this context.""" def __init__(self, bot: BotT, command: Command[CogT], interaction: discord.Interaction): self.bot = bot self.command = command self.interaction = interaction self._responded = False @overload def send(self, content: str = MISSING, *, embed: discord.Embed = MISSING, ephemeral: bool = MISSING, tts: bool = MISSING, view: discord.ui.View = MISSING, file: discord.File = MISSING) -> Coroutine[Any, Any, Union[discord.InteractionMessage, discord.WebhookMessage]]: ... @overload def send(self, content: str = MISSING, *, embed: discord.Embed = MISSING, ephemeral: bool = MISSING, tts: bool = MISSING, view: discord.ui.View = MISSING, files: list[discord.File] = MISSING) -> Coroutine[Any, Any, Union[discord.InteractionMessage, discord.WebhookMessage]]: ... @overload def send(self, content: str = MISSING, *, embeds: list[discord.Embed] = MISSING, ephemeral: bool = MISSING, tts: bool = MISSING, view: discord.ui.View = MISSING, file: discord.File = MISSING) -> Coroutine[Any, Any, Union[discord.InteractionMessage, discord.WebhookMessage]]: ... @overload def send(self, content: str = MISSING, *, embeds: list[discord.Embed] = MISSING, ephemeral: bool = MISSING, tts: bool = MISSING, view: discord.ui.View = MISSING, files: list[discord.File] = MISSING) -> Coroutine[Any, Any, Union[discord.InteractionMessage, discord.WebhookMessage]]: ... async def send(self, content = MISSING, **kwargs) -> Union[discord.InteractionMessage, discord.WebhookMessage]: """ Responds to the given interaction. If you have responded already, this will use the follow-up webhook instead. Parameters ``embed`` and ``embeds`` cannot be specified together. Parameters ``file`` and ``files`` cannot be specified together. Parameters: - content: ``str`` - - The content of the message to respond with - embed: [``discord.Embed``](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed) - - An embed to send with the message. Incompatible with ``embeds``. - embeds: ``List[``[``discord.Embed``](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed)``]`` - - A list of embeds to send with the message. Incompatible with ``embed``. - file: [``discord.File``](https://discordpy.readthedocs.io/en/master/api.html#discord.File) - - A file to send with the message. Incompatible with ``files``. - files: ``List[``[``discord.File``](https://discordpy.readthedocs.io/en/master/api.html#discord.File)``]`` - - A list of files to send with the message. Incompatible with ``file``. - ephemeral: ``bool`` - - Whether the message should be ephemeral (only visible to the interaction user). - tts: ``bool`` - - Whether the message should be played via Text To Speech. Send TTS Messages permission is required. - view: [``discord.ui.View``](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View) - - Components to attach to the sent message. Returns - [``discord.InteractionMessage``](https://discordpy.readthedocs.io/en/master/api.html#discord.InteractionMessage) if this is the first time responding. - [``discord.WebhookMessage``](https://discordpy.readthedocs.io/en/master/api.html#discord.WebhookMessage) for consecutive responses. """ if self._responded: return await self.interaction.followup.send(content, wait=True, **kwargs) await self.interaction.response.send_message(content or None, **kwargs) self._responded = True return await self.interaction.original_message() @property def cog(self) -> CogT: """The cog this command belongs to.""" return self.command.cog @property def guild(self) -> discord.Guild: """The guild this interaction was executed in.""" return self.interaction.guild # type: ignore @property def message(self) -> discord.Message: """The message that executed this interaction.""" return self.interaction.message # type: ignore @property def channel(self) -> discord.interactions.InteractionChannel: """The channel the interaction was executed in.""" return self.interaction.channel # type: ignore @property def author(self) -> discord.Member: """The user that executed this interaction.""" return self.interaction.user # type: ignore class Command(Generic[CogT]): cog: CogT func: Callable name: str guild_id: int | None def _build_command_payload(self) -> dict[str, Any]: raise NotImplementedError def _build_arguments(self, interaction: discord.Interaction, state: discord.state.ConnectionState) -> dict[str, Any]: raise NotImplementedError async def invoke(self, context: Context[BotT, CogT], **params) -> None: await self.func(self.cog, context, **params) class SlashCommand(Command[CogT]): def __init__(self, func: CmdT, **kwargs): self.func = func self.cog: CogT self.name: str = kwargs.get("name", func.__name__) self.description: str = kwargs.get("description") or func.__doc__ or "No description provided" self.guild_id: int | None = kwargs.get("guild_id") self.parameters = self._build_parameters() self._parameter_descriptions: dict[str, str] = defaultdict(lambda: "No description provided") def _build_arguments(self, interaction, state): if 'options' not in interaction.data: return {} resolved = _parse_resolved_data(interaction, interaction.data.get('resolved'), state) result = {} for option in interaction.data['options']: value = option['value'] if option['type'] in (6, 7, 8): value = resolved[int(value)] result[option['name']] = value return result def _build_parameters(self) -> dict[str, inspect.Parameter]: params = list(inspect.signature(self.func).parameters.values()) try: params.pop(0) except IndexError: raise ValueError("expected argument `self` is missing") try: params.pop(0) except IndexError: raise ValueError("expected argument `context` is missing") return {p.name: p for p in params} def _build_descriptions(self): if not hasattr(self.func, '_param_desc_'): return for k, v in self.func._param_desc_.items(): if k not in self.parameters: raise TypeError(f"@describe used to describe a non-existant parameter `{k}`") self._parameter_descriptions[k] = v def _build_command_payload(self): self._build_descriptions() payload = { "name": self.name, "description": self.description, "type": 1 } params = self.parameters if params: options = [] for name, param in params.items(): ann = param.annotation if ann is param.empty: raise TypeError(f"missing type annotation for parameter `{param.name}` for command `{self.name}`") if isinstance(ann, str): ann = eval(ann) if isinstance(ann, Range): real_t = type(ann.max) elif get_origin(ann) is Union: args = get_args(ann) real_t = args[0] else: real_t = ann typ = command_type_map[real_t] option = { 'type': typ, 'name': name, 'description': self._parameter_descriptions[name] } if param.default is param.empty: option['required'] = True if isinstance(ann, Range): option['max_value'] = ann.max option['min_value'] = ann.min elif get_origin(ann) is Union: args = get_args(ann) if not all(issubclass(k, discord.abc.GuildChannel) for k in args): raise TypeError(f"Union parameter types only supported on *Channel types") if len(args) != 3: filtered = [channel_filter[i] for i in args] option['channel_types'] = filtered elif issubclass(ann, discord.abc.GuildChannel): option['channel_types'] = [channel_filter[ann]] options.append(option) options.sort(key=lambda f: not f.get('required')) payload['options'] = options return payload class ContextMenuCommand(Command[CogT]): _type: ClassVar[int] def __init__(self, func: CtxMnT, **kwargs): self.func = func self.guild_id: int | None = kwargs.get('guild_id', None) self.name: str = kwargs.get('name', func.__name__) def _build_command_payload(self): payload = { 'name': self.name, 'type': self._type } if self.guild_id is not None: payload['guild_id'] = self.guild_id return payload def _build_arguments(self, interaction: discord.Interaction, state: discord.state.ConnectionState) -> dict[str, Any]: resolved = _parse_resolved_data(interaction, interaction.data.get('resolved'), state) # type: ignore value = resolved[int(interaction.data['target_id'])] # type: ignore return {'target': value} async def invoke(self, context: Context[BotT, CogT], **params) -> None: await self.func(self.cog, context, *params.values()) class MessageCommand(ContextMenuCommand[CogT]): _type = 3 class UserCommand(ContextMenuCommand[CogT]): _type = 2 def _parse_resolved_data(interaction: discord.Interaction, data, state: discord.state.ConnectionState): if not data: return {} assert interaction.guild resolved = {} resolved_users = data.get('users') if resolved_users: resolved_members = data['members'] for id, d in resolved_users.items(): member_data = resolved_members[id] member_data['user'] = d member = discord.Member(data=member_data, guild=interaction.guild, state=state) resolved[int(id)] = member resolved_channels = data.get('channels') if resolved_channels: for id, d in resolved_channels.items(): d['position'] = None cls, _ = discord.channel._guild_channel_factory(d['type']) channel = cls(state=state, guild=interaction.guild, data=d) resolved[int(id)] = channel resolved_messages = data.get('messages') if resolved_messages: for id, d in resolved_messages.items(): msg = discord.Message(state=state, channel=interaction.channel, data=d) # type: ignore resolved[int(id)] = msg resolved_roles = data.get('roles') if resolved_roles: for id, d in resolved_roles.items(): role = discord.Role(guild=interaction.guild, state=state, data=d) resolved[int(id)] = role return resolved class ApplicationCog(commands.Cog, Generic[BotT]): """ The cog that must be used for application commands. Attributes: - bot: [`zarena.Bot`](#class-bot_command_prefix-help_command_default-help-command-description_none-options) - - The bot instance.""" def __init__(self, bot: BotT): self.bot: BotT = bot self._commands: dict[str, Command] = {} slashes = inspect.getmembers(self, lambda c: isinstance(c, Command)) for k, v in slashes: self._commands[v.name] = v @commands.Cog.listener("on_interaction") async def _internal_interaction_handler(self, interaction: discord.Interaction): if interaction.type is not discord.InteractionType.application_command: return name = interaction.data['name'] # type: ignore command = self._commands.get(name) if not command: return state = self.bot._connection params: dict = command._build_arguments(interaction, state) ctx = Context(self.bot, command, interaction) await command.invoke(ctx, **params)
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/zarena.py
zarena.py
import types from collections import namedtuple from typing import Any, ClassVar, Dict, List, Optional, TYPE_CHECKING, Type, TypeVar __all__ = ( 'Enum', 'ChannelType', 'MessageType', 'VoiceRegion', 'SpeakingState', 'VerificationLevel', 'ContentFilter', 'Status', 'DefaultAvatar', 'AuditLogAction', 'AuditLogActionCategory', 'UserFlags', 'ActivityType', 'NotificationLevel', 'TeamMembershipState', 'WebhookType', 'ExpireBehaviour', 'ExpireBehavior', 'StickerType', 'StickerFormatType', 'InviteTarget', 'VideoQualityMode', 'ComponentType', 'ButtonStyle', 'StagePrivacyLevel', 'InteractionType', 'InteractionResponseType', 'NSFWLevel', ) def _create_value_cls(name, comparable): cls = namedtuple('_EnumValue_' + name, 'name value') cls.__repr__ = lambda self: f'<{name}.{self.name}: {self.value!r}>' cls.__str__ = lambda self: f'{name}.{self.name}' if comparable: cls.__le__ = lambda self, other: isinstance(other, self.__class__) and self.value <= other.value cls.__ge__ = lambda self, other: isinstance(other, self.__class__) and self.value >= other.value cls.__lt__ = lambda self, other: isinstance(other, self.__class__) and self.value < other.value cls.__gt__ = lambda self, other: isinstance(other, self.__class__) and self.value > other.value return cls def _is_descriptor(obj): return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__') class EnumMeta(type): if TYPE_CHECKING: __name__: ClassVar[str] _enum_member_names_: ClassVar[List[str]] _enum_member_map_: ClassVar[Dict[str, Any]] _enum_value_map_: ClassVar[Dict[Any, Any]] def __new__(cls, name, bases, attrs, *, comparable: bool = False): value_mapping = {} member_mapping = {} member_names = [] value_cls = _create_value_cls(name, comparable) for key, value in list(attrs.items()): is_descriptor = _is_descriptor(value) if key[0] == '_' and not is_descriptor: continue # Special case classmethod to just pass through if isinstance(value, classmethod): continue if is_descriptor: setattr(value_cls, key, value) del attrs[key] continue try: new_value = value_mapping[value] except KeyError: new_value = value_cls(name=key, value=value) value_mapping[value] = new_value member_names.append(key) member_mapping[key] = new_value attrs[key] = new_value attrs['_enum_value_map_'] = value_mapping attrs['_enum_member_map_'] = member_mapping attrs['_enum_member_names_'] = member_names attrs['_enum_value_cls_'] = value_cls actual_cls = super().__new__(cls, name, bases, attrs) value_cls._actual_enum_cls_ = actual_cls # type: ignore return actual_cls def __iter__(cls): return (cls._enum_member_map_[name] for name in cls._enum_member_names_) def __reversed__(cls): return (cls._enum_member_map_[name] for name in reversed(cls._enum_member_names_)) def __len__(cls): return len(cls._enum_member_names_) def __repr__(cls): return f'<enum {cls.__name__}>' @property def __members__(cls): return types.MappingProxyType(cls._enum_member_map_) def __call__(cls, value): try: return cls._enum_value_map_[value] except (KeyError, TypeError): raise ValueError(f"{value!r} is not a valid {cls.__name__}") def __getitem__(cls, key): return cls._enum_member_map_[key] def __setattr__(cls, name, value): raise TypeError('Enums are immutable.') def __delattr__(cls, attr): raise TypeError('Enums are immutable') def __instancecheck__(self, instance): # isinstance(x, Y) # -> __instancecheck__(Y, x) try: return instance._actual_enum_cls_ is self except AttributeError: return False if TYPE_CHECKING: from enum import Enum else: class Enum(metaclass=EnumMeta): @classmethod def try_value(cls, value): try: return cls._enum_value_map_[value] except (KeyError, TypeError): return value class ChannelType(Enum): text = 0 private = 1 voice = 2 group = 3 category = 4 news = 5 store = 6 news_thread = 10 public_thread = 11 private_thread = 12 stage_voice = 13 def __str__(self): return self.name class MessageType(Enum): default = 0 recipient_add = 1 recipient_remove = 2 call = 3 channel_name_change = 4 channel_icon_change = 5 pins_add = 6 new_member = 7 premium_guild_subscription = 8 premium_guild_tier_1 = 9 premium_guild_tier_2 = 10 premium_guild_tier_3 = 11 channel_follow_add = 12 guild_stream = 13 guild_discovery_disqualified = 14 guild_discovery_requalified = 15 guild_discovery_grace_period_initial_warning = 16 guild_discovery_grace_period_final_warning = 17 thread_created = 18 reply = 19 application_command = 20 thread_starter_message = 21 guild_invite_reminder = 22 class VoiceRegion(Enum): us_west = 'us-west' us_east = 'us-east' us_south = 'us-south' us_central = 'us-central' eu_west = 'eu-west' eu_central = 'eu-central' singapore = 'singapore' london = 'london' sydney = 'sydney' amsterdam = 'amsterdam' frankfurt = 'frankfurt' brazil = 'brazil' hongkong = 'hongkong' russia = 'russia' japan = 'japan' southafrica = 'southafrica' south_korea = 'south-korea' india = 'india' europe = 'europe' dubai = 'dubai' vip_us_east = 'vip-us-east' vip_us_west = 'vip-us-west' vip_amsterdam = 'vip-amsterdam' def __str__(self): return self.value class SpeakingState(Enum): none = 0 voice = 1 soundshare = 2 priority = 4 def __str__(self): return self.name def __int__(self): return self.value class VerificationLevel(Enum, comparable=True): none = 0 low = 1 medium = 2 high = 3 highest = 4 def __str__(self): return self.name class ContentFilter(Enum, comparable=True): disabled = 0 no_role = 1 all_members = 2 def __str__(self): return self.name class Status(Enum): online = 'online' offline = 'offline' idle = 'idle' dnd = 'dnd' do_not_disturb = 'dnd' invisible = 'invisible' def __str__(self): return self.value class DefaultAvatar(Enum): blurple = 0 grey = 1 gray = 1 green = 2 orange = 3 red = 4 def __str__(self): return self.name class NotificationLevel(Enum, comparable=True): all_messages = 0 only_mentions = 1 class AuditLogActionCategory(Enum): create = 1 delete = 2 update = 3 class AuditLogAction(Enum): # fmt: off guild_update = 1 channel_create = 10 channel_update = 11 channel_delete = 12 overwrite_create = 13 overwrite_update = 14 overwrite_delete = 15 kick = 20 member_prune = 21 ban = 22 unban = 23 member_update = 24 member_role_update = 25 member_move = 26 member_disconnect = 27 bot_add = 28 role_create = 30 role_update = 31 role_delete = 32 invite_create = 40 invite_update = 41 invite_delete = 42 webhook_create = 50 webhook_update = 51 webhook_delete = 52 emoji_create = 60 emoji_update = 61 emoji_delete = 62 message_delete = 72 message_bulk_delete = 73 message_pin = 74 message_unpin = 75 integration_create = 80 integration_update = 81 integration_delete = 82 stage_instance_create = 83 stage_instance_update = 84 stage_instance_delete = 85 sticker_create = 90 sticker_update = 91 sticker_delete = 92 thread_create = 110 thread_update = 111 thread_delete = 112 # fmt: on @property def category(self) -> Optional[AuditLogActionCategory]: # fmt: off lookup: Dict[AuditLogAction, Optional[AuditLogActionCategory]] = { AuditLogAction.guild_update: AuditLogActionCategory.update, AuditLogAction.channel_create: AuditLogActionCategory.create, AuditLogAction.channel_update: AuditLogActionCategory.update, AuditLogAction.channel_delete: AuditLogActionCategory.delete, AuditLogAction.overwrite_create: AuditLogActionCategory.create, AuditLogAction.overwrite_update: AuditLogActionCategory.update, AuditLogAction.overwrite_delete: AuditLogActionCategory.delete, AuditLogAction.kick: None, AuditLogAction.member_prune: None, AuditLogAction.ban: None, AuditLogAction.unban: None, AuditLogAction.member_update: AuditLogActionCategory.update, AuditLogAction.member_role_update: AuditLogActionCategory.update, AuditLogAction.member_move: None, AuditLogAction.member_disconnect: None, AuditLogAction.bot_add: None, AuditLogAction.role_create: AuditLogActionCategory.create, AuditLogAction.role_update: AuditLogActionCategory.update, AuditLogAction.role_delete: AuditLogActionCategory.delete, AuditLogAction.invite_create: AuditLogActionCategory.create, AuditLogAction.invite_update: AuditLogActionCategory.update, AuditLogAction.invite_delete: AuditLogActionCategory.delete, AuditLogAction.webhook_create: AuditLogActionCategory.create, AuditLogAction.webhook_update: AuditLogActionCategory.update, AuditLogAction.webhook_delete: AuditLogActionCategory.delete, AuditLogAction.emoji_create: AuditLogActionCategory.create, AuditLogAction.emoji_update: AuditLogActionCategory.update, AuditLogAction.emoji_delete: AuditLogActionCategory.delete, AuditLogAction.message_delete: AuditLogActionCategory.delete, AuditLogAction.message_bulk_delete: AuditLogActionCategory.delete, AuditLogAction.message_pin: None, AuditLogAction.message_unpin: None, AuditLogAction.integration_create: AuditLogActionCategory.create, AuditLogAction.integration_update: AuditLogActionCategory.update, AuditLogAction.integration_delete: AuditLogActionCategory.delete, AuditLogAction.stage_instance_create: AuditLogActionCategory.create, AuditLogAction.stage_instance_update: AuditLogActionCategory.update, AuditLogAction.stage_instance_delete: AuditLogActionCategory.delete, AuditLogAction.sticker_create: AuditLogActionCategory.create, AuditLogAction.sticker_update: AuditLogActionCategory.update, AuditLogAction.sticker_delete: AuditLogActionCategory.delete, AuditLogAction.thread_create: AuditLogActionCategory.create, AuditLogAction.thread_update: AuditLogActionCategory.update, AuditLogAction.thread_delete: AuditLogActionCategory.delete, } # fmt: on return lookup[self] @property def target_type(self) -> Optional[str]: v = self.value if v == -1: return 'all' elif v < 10: return 'guild' elif v < 20: return 'channel' elif v < 30: return 'user' elif v < 40: return 'role' elif v < 50: return 'invite' elif v < 60: return 'webhook' elif v < 70: return 'emoji' elif v == 73: return 'channel' elif v < 80: return 'message' elif v < 83: return 'integration' elif v < 90: return 'stage_instance' elif v < 93: return 'sticker' elif v < 113: return 'thread' class UserFlags(Enum): staff = 1 partner = 2 hypesquad = 4 bug_hunter = 8 mfa_sms = 16 premium_promo_dismissed = 32 hypesquad_bravery = 64 hypesquad_brilliance = 128 hypesquad_balance = 256 early_supporter = 512 team_user = 1024 system = 4096 has_unread_urgent_messages = 8192 bug_hunter_level_2 = 16384 verified_bot = 65536 verified_bot_developer = 131072 discord_certified_moderator = 262144 class ActivityType(Enum): unknown = -1 playing = 0 streaming = 1 listening = 2 watching = 3 custom = 4 competing = 5 def __int__(self): return self.value class TeamMembershipState(Enum): invited = 1 accepted = 2 class WebhookType(Enum): incoming = 1 channel_follower = 2 application = 3 class ExpireBehaviour(Enum): remove_role = 0 kick = 1 ExpireBehavior = ExpireBehaviour class StickerType(Enum): standard = 1 guild = 2 class StickerFormatType(Enum): png = 1 apng = 2 lottie = 3 @property def file_extension(self) -> str: # fmt: off lookup: Dict[StickerFormatType, str] = { StickerFormatType.png: 'png', StickerFormatType.apng: 'png', StickerFormatType.lottie: 'json', } # fmt: on return lookup[self] class InviteTarget(Enum): unknown = 0 stream = 1 embedded_application = 2 class InteractionType(Enum): ping = 1 application_command = 2 component = 3 class InteractionResponseType(Enum): pong = 1 # ack = 2 (deprecated) # channel_message = 3 (deprecated) channel_message = 4 # (with source) deferred_channel_message = 5 # (with source) deferred_message_update = 6 # for components message_update = 7 # for components class VideoQualityMode(Enum): auto = 1 full = 2 def __int__(self): return self.value class ComponentType(Enum): action_row = 1 button = 2 select = 3 def __int__(self): return self.value class ButtonStyle(Enum): primary = 1 secondary = 2 success = 3 danger = 4 link = 5 # Aliases blurple = 1 grey = 2 gray = 2 green = 3 red = 4 url = 5 def __int__(self): return self.value class StagePrivacyLevel(Enum): public = 1 closed = 2 guild_only = 2 class NSFWLevel(Enum, comparable=True): default = 0 explicit = 1 safe = 2 age_restricted = 3 T = TypeVar('T') def create_unknown_value(cls: Type[T], val: Any) -> T: value_cls = cls._enum_value_cls_ # type: ignore name = f'unknown_{val}' return value_cls(name=name, value=val) 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._enum_value_map_[val] # type: ignore except (KeyError, TypeError, AttributeError): return create_unknown_value(cls, val)
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/enums.py
enums.py
from __future__ import annotations from typing import TYPE_CHECKING, Optional, Set, List if TYPE_CHECKING: from .types.raw_models import ( MessageDeleteEvent, BulkMessageDeleteEvent, ReactionActionEvent, MessageUpdateEvent, ReactionClearEvent, ReactionClearEmojiEvent, IntegrationDeleteEvent ) from .message import Message from .partial_emoji import PartialEmoji from .member import Member __all__ = ( 'RawMessageDeleteEvent', 'RawBulkMessageDeleteEvent', 'RawMessageUpdateEvent', 'RawReactionActionEvent', 'RawReactionClearEvent', 'RawReactionClearEmojiEvent', 'RawIntegrationDeleteEvent', ) class _RawReprMixin: def __repr__(self) -> str: value = ' '.join(f'{attr}={getattr(self, attr)!r}' for attr in self.__slots__) return f'<{self.__class__.__name__} {value}>' class RawMessageDeleteEvent(_RawReprMixin): """Represents the event payload for a :func:`on_raw_message_delete` event. Attributes ------------ channel_id: :class:`int` The channel ID where the deletion took place. guild_id: Optional[:class:`int`] The guild ID where the deletion took place, if applicable. message_id: :class:`int` The message ID that got deleted. cached_message: Optional[:class:`Message`] The cached message, if found in the internal message cache. """ __slots__ = ('message_id', 'channel_id', 'guild_id', 'cached_message') def __init__(self, data: MessageDeleteEvent) -> None: self.message_id: int = int(data['id']) self.channel_id: int = int(data['channel_id']) self.cached_message: Optional[Message] = None try: self.guild_id: Optional[int] = int(data['guild_id']) except KeyError: self.guild_id: Optional[int] = None class RawBulkMessageDeleteEvent(_RawReprMixin): """Represents the event payload for a :func:`on_raw_bulk_message_delete` event. Attributes ----------- message_ids: Set[:class:`int`] A :class:`set` of the message IDs that were deleted. channel_id: :class:`int` The channel ID where the message got deleted. guild_id: Optional[:class:`int`] The guild ID where the message got deleted, if applicable. cached_messages: List[:class:`Message`] The cached messages, if found in the internal message cache. """ __slots__ = ('message_ids', 'channel_id', 'guild_id', 'cached_messages') def __init__(self, data: BulkMessageDeleteEvent) -> None: self.message_ids: Set[int] = {int(x) for x in data.get('ids', [])} self.channel_id: int = int(data['channel_id']) self.cached_messages: List[Message] = [] try: self.guild_id: Optional[int] = int(data['guild_id']) except KeyError: self.guild_id: Optional[int] = None class RawMessageUpdateEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_message_edit` event. Attributes ----------- message_id: :class:`int` The message ID that got updated. channel_id: :class:`int` The channel ID where the update took place. .. versionadded:: 1.3 guild_id: Optional[:class:`int`] The guild ID where the message got updated, if applicable. .. versionadded:: 1.7 data: :class:`dict` The raw data given by the `gateway <https://discord.com/developers/docs/topics/gateway#message-update>`_ cached_message: Optional[:class:`Message`] The cached message, if found in the internal message cache. Represents the message before it is modified by the data in :attr:`RawMessageUpdateEvent.data`. """ __slots__ = ('message_id', 'channel_id', 'guild_id', 'data', 'cached_message') def __init__(self, data: MessageUpdateEvent) -> None: self.message_id: int = int(data['id']) self.channel_id: int = int(data['channel_id']) self.data: MessageUpdateEvent = data self.cached_message: Optional[Message] = None try: self.guild_id: Optional[int] = int(data['guild_id']) except KeyError: self.guild_id: Optional[int] = None class RawReactionActionEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_reaction_add` or :func:`on_raw_reaction_remove` event. Attributes ----------- message_id: :class:`int` The message ID that got or lost a reaction. user_id: :class:`int` The user ID who added the reaction or whose reaction was removed. channel_id: :class:`int` The channel ID where the reaction got added or removed. guild_id: Optional[:class:`int`] The guild ID where the reaction got added or removed, if applicable. emoji: :class:`PartialEmoji` The custom or unicode emoji being used. member: Optional[:class:`Member`] The member who added the reaction. Only available if `event_type` is `REACTION_ADD` and the reaction is inside a guild. .. versionadded:: 1.3 event_type: :class:`str` The event type that triggered this action. Can be ``REACTION_ADD`` for reaction addition or ``REACTION_REMOVE`` for reaction removal. .. versionadded:: 1.3 """ __slots__ = ('message_id', 'user_id', 'channel_id', 'guild_id', 'emoji', 'event_type', 'member') def __init__(self, data: ReactionActionEvent, emoji: PartialEmoji, event_type: str) -> None: self.message_id: int = int(data['message_id']) self.channel_id: int = int(data['channel_id']) self.user_id: int = int(data['user_id']) self.emoji: PartialEmoji = emoji self.event_type: str = event_type self.member: Optional[Member] = None try: self.guild_id: Optional[int] = int(data['guild_id']) except KeyError: self.guild_id: Optional[int] = None class RawReactionClearEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_reaction_clear` event. Attributes ----------- message_id: :class:`int` The message ID that got its reactions cleared. channel_id: :class:`int` The channel ID where the reactions got cleared. guild_id: Optional[:class:`int`] The guild ID where the reactions got cleared. """ __slots__ = ('message_id', 'channel_id', 'guild_id') def __init__(self, data: ReactionClearEvent) -> None: self.message_id: int = int(data['message_id']) self.channel_id: int = int(data['channel_id']) try: self.guild_id: Optional[int] = int(data['guild_id']) except KeyError: self.guild_id: Optional[int] = None class RawReactionClearEmojiEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_reaction_clear_emoji` event. .. versionadded:: 1.3 Attributes ----------- message_id: :class:`int` The message ID that got its reactions cleared. channel_id: :class:`int` The channel ID where the reactions got cleared. guild_id: Optional[:class:`int`] The guild ID where the reactions got cleared. emoji: :class:`PartialEmoji` The custom or unicode emoji being removed. """ __slots__ = ('message_id', 'channel_id', 'guild_id', 'emoji') def __init__(self, data: ReactionClearEmojiEvent, emoji: PartialEmoji) -> None: self.emoji: PartialEmoji = emoji self.message_id: int = int(data['message_id']) self.channel_id: int = int(data['channel_id']) try: self.guild_id: Optional[int] = int(data['guild_id']) except KeyError: self.guild_id: Optional[int] = None class RawIntegrationDeleteEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_integration_delete` event. .. versionadded:: 2.0 Attributes ----------- integration_id: :class:`int` The ID of the integration that got deleted. application_id: Optional[:class:`int`] The ID of the bot/OAuth2 application for this deleted integration. guild_id: :class:`int` The guild ID where the integration got deleted. """ __slots__ = ('integration_id', 'application_id', 'guild_id') def __init__(self, data: IntegrationDeleteEvent) -> None: self.integration_id: int = int(data['id']) self.guild_id: int = int(data['guild_id']) try: self.application_id: Optional[int] = int(data['application_id']) except KeyError: self.application_id: Optional[int] = None
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/raw_models.py
raw_models.py
from __future__ import annotations import array import asyncio import collections.abc from typing import ( Any, AsyncIterator, Callable, Dict, ForwardRef, Generic, Iterable, Iterator, List, Literal, Mapping, Optional, Protocol, Sequence, Tuple, Type, TypeVar, Union, overload, TYPE_CHECKING, ) import unicodedata from base64 import b64encode from bisect import bisect_left import datetime import functools from inspect import isawaitable as _isawaitable, signature as _signature from operator import attrgetter import json import re import sys import types import warnings from .errors import InvalidArgument try: import orjson except ModuleNotFoundError: HAS_ORJSON = False else: HAS_ORJSON = True __all__ = ( 'oauth_url', 'snowflake_time', 'time_snowflake', 'find', 'get', 'sleep_until', 'utcnow', 'remove_markdown', 'escape_markdown', 'escape_mentions', 'as_chunks', 'format_dt', ) DISCORD_EPOCH = 1420070400000 class _MissingSentinel: def __eq__(self, other): return False def __bool__(self): return False def __repr__(self): return '...' MISSING: Any = _MissingSentinel() class _cached_property: def __init__(self, function): self.function = function self.__doc__ = getattr(function, '__doc__') def __get__(self, instance, owner): if instance is None: return self value = self.function(instance) setattr(instance, self.function.__name__, value) return value if TYPE_CHECKING: from functools import cached_property as cached_property from typing_extensions import ParamSpec from .permissions import Permissions from .abc import Snowflake from .invite import Invite from .template import Template class _RequestLike(Protocol): headers: Mapping[str, Any] P = ParamSpec('P') else: cached_property = _cached_property T = TypeVar('T') T_co = TypeVar('T_co', covariant=True) _Iter = Union[Iterator[T], AsyncIterator[T]] class CachedSlotProperty(Generic[T, T_co]): def __init__(self, name: str, function: Callable[[T], T_co]) -> None: self.name = name self.function = function self.__doc__ = getattr(function, '__doc__') @overload def __get__(self, instance: None, owner: Type[T]) -> CachedSlotProperty[T, T_co]: ... @overload def __get__(self, instance: T, owner: Type[T]) -> T_co: ... def __get__(self, instance: Optional[T], owner: Type[T]) -> Any: if instance is None: return self try: return getattr(instance, self.name) except AttributeError: value = self.function(instance) setattr(instance, self.name, value) return value class classproperty(Generic[T_co]): def __init__(self, fget: Callable[[Any], T_co]) -> None: self.fget = fget def __get__(self, instance: Optional[Any], owner: Type[Any]) -> T_co: return self.fget(owner) def __set__(self, instance, value) -> None: raise AttributeError('cannot set attribute') def cached_slot_property(name: str) -> Callable[[Callable[[T], T_co]], CachedSlotProperty[T, T_co]]: def decorator(func: Callable[[T], T_co]) -> CachedSlotProperty[T, T_co]: return CachedSlotProperty(name, func) return decorator class SequenceProxy(Generic[T_co], collections.abc.Sequence): """Read-only proxy of a Sequence.""" def __init__(self, proxied: Sequence[T_co]): self.__proxied = proxied def __getitem__(self, idx: int) -> T_co: return self.__proxied[idx] def __len__(self) -> int: return len(self.__proxied) def __contains__(self, item: Any) -> bool: return item in self.__proxied def __iter__(self) -> Iterator[T_co]: return iter(self.__proxied) def __reversed__(self) -> Iterator[T_co]: return reversed(self.__proxied) def index(self, value: Any, *args, **kwargs) -> int: return self.__proxied.index(value, *args, **kwargs) def count(self, value: Any) -> int: return self.__proxied.count(value) @overload def parse_time(timestamp: None) -> None: ... @overload def parse_time(timestamp: str) -> datetime.datetime: ... @overload def parse_time(timestamp: Optional[str]) -> Optional[datetime.datetime]: ... def parse_time(timestamp: Optional[str]) -> Optional[datetime.datetime]: if timestamp: return datetime.datetime.fromisoformat(timestamp) return None def copy_doc(original: Callable) -> Callable[[T], T]: def decorator(overriden: T) -> T: overriden.__doc__ = original.__doc__ overriden.__signature__ = _signature(original) # type: ignore return overriden return decorator def deprecated(instead: Optional[str] = None) -> Callable[[Callable[P, T]], Callable[P, T]]: def actual_decorator(func: Callable[P, T]) -> Callable[P, T]: @functools.wraps(func) def decorated(*args: P.args, **kwargs: P.kwargs) -> T: warnings.simplefilter('always', DeprecationWarning) # turn off filter if instead: fmt = "{0.__name__} is deprecated, use {1} instead." else: fmt = '{0.__name__} is deprecated.' warnings.warn(fmt.format(func, instead), stacklevel=3, category=DeprecationWarning) warnings.simplefilter('default', DeprecationWarning) # reset filter return func(*args, **kwargs) return decorated return actual_decorator def oauth_url( client_id: Union[int, str], *, permissions: Permissions = MISSING, guild: Snowflake = MISSING, redirect_uri: str = MISSING, scopes: Iterable[str] = MISSING, disable_guild_select: bool = False, ) -> str: """A helper function that returns the OAuth2 URL for inviting the bot into guilds. Parameters ----------- client_id: Union[:class:`int`, :class:`str`] The client ID for your bot. permissions: :class:`~discord.Permissions` The permissions you're requesting. If not given then you won't be requesting any permissions. guild: :class:`~discord.abc.Snowflake` The guild to pre-select in the authorization screen, if available. redirect_uri: :class:`str` An optional valid redirect URI. scopes: Iterable[:class:`str`] An optional valid list of scopes. Defaults to ``('bot',)``. .. versionadded:: 1.7 disable_guild_select: :class:`bool` Whether to disallow the user from changing the guild dropdown. .. versionadded:: 2.0 Returns -------- :class:`str` The OAuth2 URL for inviting the bot into guilds. """ url = f'https://discord.com/oauth2/authorize?client_id={client_id}' url += '&scope=' + '+'.join(scopes or ('bot',)) if permissions is not MISSING: url += f'&permissions={permissions.value}' if guild is not MISSING: url += f'&guild_id={guild.id}' if redirect_uri is not MISSING: from urllib.parse import urlencode url += '&response_type=code&' + urlencode({'redirect_uri': redirect_uri}) if disable_guild_select: url += '&disable_guild_select=true' return url def snowflake_time(id: int) -> datetime.datetime: """ Parameters ----------- id: :class:`int` The snowflake ID. Returns -------- :class:`datetime.datetime` An aware datetime in UTC representing the creation time of the snowflake. """ timestamp = ((id >> 22) + DISCORD_EPOCH) / 1000 return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc) def time_snowflake(dt: datetime.datetime, high: bool = False) -> int: """Returns a numeric snowflake pretending to be created at the given date. When using as the lower end of a range, use ``time_snowflake(high=False) - 1`` to be inclusive, ``high=True`` to be exclusive. When using as the higher end of a range, use ``time_snowflake(high=True) + 1`` to be inclusive, ``high=False`` to be exclusive Parameters ----------- dt: :class:`datetime.datetime` A datetime object to convert to a snowflake. If naive, the timezone is assumed to be local time. high: :class:`bool` Whether or not to set the lower 22 bit to high or low. Returns -------- :class:`int` The snowflake representing the time given. """ discord_millis = int(dt.timestamp() * 1000 - DISCORD_EPOCH) return (discord_millis << 22) + (2 ** 22 - 1 if high else 0) def find(predicate: Callable[[T], Any], seq: Iterable[T]) -> Optional[T]: """A helper to return the first element found in the sequence that meets the predicate. For example: :: member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members) would find the first :class:`~discord.Member` whose name is 'Mighty' and return it. If an entry is not found, then ``None`` is returned. This is different from :func:`py:filter` due to the fact it stops the moment it finds a valid entry. Parameters ----------- predicate A function that returns a boolean-like result. seq: :class:`collections.abc.Iterable` The iterable to search through. """ for element in seq: if predicate(element): return element return None def get(iterable: Iterable[T], **attrs: Any) -> Optional[T]: r"""A helper that returns the first element in the iterable that meets all the traits passed in ``attrs``. This is an alternative for :func:`~discord.utils.find`. When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them. To have a nested attribute search (i.e. search by ``x.y``) then pass in ``x__y`` as the keyword argument. If nothing is found that matches the attributes passed, then ``None`` is returned. Examples --------- Basic usage: .. code-block:: python3 member = discord.utils.get(message.guild.members, name='Foo') Multiple attribute matching: .. code-block:: python3 channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000) Nested attribute matching: .. code-block:: python3 channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general') Parameters ----------- iterable An iterable to search through. \*\*attrs Keyword arguments that denote attributes to search with. """ # global -> local _all = all attrget = attrgetter # Special case the single element call if len(attrs) == 1: k, v = attrs.popitem() pred = attrget(k.replace('__', '.')) for elem in iterable: if pred(elem) == v: return elem return None converted = [(attrget(attr.replace('__', '.')), value) for attr, value in attrs.items()] for elem in iterable: if _all(pred(elem) == value for pred, value in converted): return elem return None def _unique(iterable: Iterable[T]) -> List[T]: return [x for x in dict.fromkeys(iterable)] def _get_as_snowflake(data: Any, key: str) -> Optional[int]: try: value = data[key] except KeyError: return None else: return value and int(value) def _get_mime_type_for_image(data: bytes): if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'): return 'image/png' elif data[0:3] == b'\xff\xd8\xff' or data[6:10] in (b'JFIF', b'Exif'): return 'image/jpeg' elif data.startswith((b'\x47\x49\x46\x38\x37\x61', b'\x47\x49\x46\x38\x39\x61')): return 'image/gif' elif data.startswith(b'RIFF') and data[8:12] == b'WEBP': return 'image/webp' else: raise InvalidArgument('Unsupported image type given') def _bytes_to_base64_data(data: bytes) -> str: fmt = 'data:{mime};base64,{data}' mime = _get_mime_type_for_image(data) b64 = b64encode(data).decode('ascii') return fmt.format(mime=mime, data=b64) if HAS_ORJSON: def _to_json(obj: Any) -> str: # type: ignore return orjson.dumps(obj).decode('utf-8') _from_json = orjson.loads # type: ignore else: def _to_json(obj: Any) -> str: return json.dumps(obj, separators=(',', ':'), ensure_ascii=True) _from_json = json.loads def _parse_ratelimit_header(request: Any, *, use_clock: bool = False) -> float: reset_after: Optional[str] = request.headers.get('X-Ratelimit-Reset-After') if use_clock or not reset_after: utc = datetime.timezone.utc now = datetime.datetime.now(utc) reset = datetime.datetime.fromtimestamp(float(request.headers['X-Ratelimit-Reset']), utc) return (reset - now).total_seconds() else: return float(reset_after) async def maybe_coroutine(f, *args, **kwargs): value = f(*args, **kwargs) if _isawaitable(value): return await value else: return value async def async_all(gen, *, check=_isawaitable): for elem in gen: if check(elem): elem = await elem if not elem: return False return True async def sane_wait_for(futures, *, timeout): ensured = [asyncio.ensure_future(fut) for fut in futures] done, pending = await asyncio.wait(ensured, timeout=timeout, return_when=asyncio.ALL_COMPLETED) if len(pending) != 0: raise asyncio.TimeoutError() return done def get_slots(cls: Type[Any]) -> Iterator[str]: for mro in reversed(cls.__mro__): try: yield from mro.__slots__ except AttributeError: continue def compute_timedelta(dt: datetime.datetime): if dt.tzinfo is None: dt = dt.astimezone() now = datetime.datetime.now(datetime.timezone.utc) return max((dt - now).total_seconds(), 0) async def sleep_until(when: datetime.datetime, result: Optional[T] = None) -> Optional[T]: """|coro| Sleep until a specified time. If the time supplied is in the past this function will yield instantly. .. versionadded:: 1.3 Parameters ----------- when: :class:`datetime.datetime` The timestamp in which to sleep until. If the datetime is naive then it is assumed to be local time. result: Any If provided is returned to the caller when the coroutine completes. """ delta = compute_timedelta(when) return await asyncio.sleep(delta, result) def utcnow() -> datetime.datetime: """A helper function to return an aware UTC datetime representing the current time. This should be preferred to :meth:`datetime.datetime.utcnow` since it is an aware datetime, compared to the naive datetime in the standard library. .. versionadded:: 2.0 Returns -------- :class:`datetime.datetime` The current aware datetime in UTC. """ return datetime.datetime.now(datetime.timezone.utc) def valid_icon_size(size: int) -> bool: """Icons must be power of 2 within [16, 4096].""" return not size & (size - 1) and 4096 >= size >= 16 class SnowflakeList(array.array): """Internal data storage class to efficiently store a list of snowflakes. This should have the following characteristics: - Low memory usage - O(n) iteration (obviously) - O(n log n) initial creation if data is unsorted - O(log n) search and indexing - O(n) insertion """ __slots__ = () if TYPE_CHECKING: def __init__(self, data: Iterable[int], *, is_sorted: bool = False): ... def __new__(cls, data: Iterable[int], *, is_sorted: bool = False): return array.array.__new__(cls, 'Q', data if is_sorted else sorted(data)) # type: ignore def add(self, element: int) -> None: i = bisect_left(self, element) self.insert(i, element) def get(self, element: int) -> Optional[int]: i = bisect_left(self, element) return self[i] if i != len(self) and self[i] == element else None def has(self, element: int) -> bool: i = bisect_left(self, element) return i != len(self) and self[i] == element _IS_ASCII = re.compile(r'^[\x00-\x7f]+$') def _string_width(string: str, *, _IS_ASCII=_IS_ASCII) -> int: """Returns string's width.""" match = _IS_ASCII.match(string) if match: return match.endpos UNICODE_WIDE_CHAR_TYPE = 'WFA' func = unicodedata.east_asian_width return sum(2 if func(char) in UNICODE_WIDE_CHAR_TYPE else 1 for char in string) def resolve_invite(invite: Union[Invite, str]) -> str: """ Resolves an invite from a :class:`~discord.Invite`, URL or code. Parameters ----------- invite: Union[:class:`~discord.Invite`, :class:`str`] The invite. Returns -------- :class:`str` The invite code. """ from .invite import Invite # circular import if isinstance(invite, Invite): return invite.code else: rx = r'(?:https?\:\/\/)?discord(?:\.gg|(?:app)?\.com\/invite)\/(.+)' m = re.match(rx, invite) if m: return m.group(1) return invite def resolve_template(code: Union[Template, str]) -> str: """ Resolves a template code from a :class:`~discord.Template`, URL or code. .. versionadded:: 1.4 Parameters ----------- code: Union[:class:`~discord.Template`, :class:`str`] The code. Returns -------- :class:`str` The template code. """ from .template import Template # circular import if isinstance(code, Template): return code.code else: rx = r'(?:https?\:\/\/)?discord(?:\.new|(?:app)?\.com\/template)\/(.+)' m = re.match(rx, code) if m: return m.group(1) return code _MARKDOWN_ESCAPE_SUBREGEX = '|'.join(r'\{0}(?=([\s\S]*((?<!\{0})\{0})))'.format(c) for c in ('*', '`', '_', '~', '|')) _MARKDOWN_ESCAPE_COMMON = r'^>(?:>>)?\s|\[.+\]\(.+\)' _MARKDOWN_ESCAPE_REGEX = re.compile(fr'(?P<markdown>{_MARKDOWN_ESCAPE_SUBREGEX}|{_MARKDOWN_ESCAPE_COMMON})', re.MULTILINE) _URL_REGEX = r'(?P<url><[^: >]+:\/[^ >]+>|(?:https?|steam):\/\/[^\s<]+[^<.,:;\"\'\]\s])' _MARKDOWN_STOCK_REGEX = fr'(?P<markdown>[_\\~|\*`]|{_MARKDOWN_ESCAPE_COMMON})' def remove_markdown(text: str, *, ignore_links: bool = True) -> str: """A helper function that removes markdown characters. .. versionadded:: 1.7 .. note:: This function is not markdown aware and may remove meaning from the original text. For example, if the input contains ``10 * 5`` then it will be converted into ``10 5``. Parameters ----------- text: :class:`str` The text to remove markdown from. ignore_links: :class:`bool` Whether to leave links alone when removing markdown. For example, if a URL in the text contains characters such as ``_`` then it will be left alone. Defaults to ``True``. Returns -------- :class:`str` The text with the markdown special characters removed. """ def replacement(match): groupdict = match.groupdict() return groupdict.get('url', '') regex = _MARKDOWN_STOCK_REGEX if ignore_links: regex = f'(?:{_URL_REGEX}|{regex})' return re.sub(regex, replacement, text, 0, re.MULTILINE) def escape_markdown(text: str, *, as_needed: bool = False, ignore_links: bool = True) -> str: r"""A helper function that escapes Discord's markdown. Parameters ----------- text: :class:`str` The text to escape markdown from. as_needed: :class:`bool` Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it's not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**`` instead of ``\*\*hello\*\*``. Note however that this can open you up to some clever syntax abuse. Defaults to ``False``. ignore_links: :class:`bool` Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as ``_`` then it will be left alone. This option is not supported with ``as_needed``. Defaults to ``True``. Returns -------- :class:`str` The text with the markdown special characters escaped with a slash. """ if not as_needed: def replacement(match): groupdict = match.groupdict() is_url = groupdict.get('url') if is_url: return is_url return '\\' + groupdict['markdown'] regex = _MARKDOWN_STOCK_REGEX if ignore_links: regex = f'(?:{_URL_REGEX}|{regex})' return re.sub(regex, replacement, text, 0, re.MULTILINE) else: text = re.sub(r'\\', r'\\\\', text) return _MARKDOWN_ESCAPE_REGEX.sub(r'\\\1', text) def escape_mentions(text: str) -> str: """A helper function that escapes everyone, here, role, and user mentions. .. note:: This does not include channel mentions. .. note:: For more granular control over what mentions should be escaped within messages, refer to the :class:`~discord.AllowedMentions` class. Parameters ----------- text: :class:`str` The text to escape mentions from. Returns -------- :class:`str` The text with the mentions removed. """ return re.sub(r'@(everyone|here|[!&]?[0-9]{17,20})', '@\u200b\\1', text) 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 @overload def as_chunks(iterator: Iterator[T], max_size: int) -> Iterator[List[T]]: ... @overload def as_chunks(iterator: AsyncIterator[T], max_size: int) -> AsyncIterator[List[T]]: ... 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) PY_310 = sys.version_info >= (3, 10) def flatten_literal_params(parameters: Iterable[Any]) -> Tuple[Any, ...]: params = [] literal_cls = type(Literal[0]) for p in parameters: if isinstance(p, literal_cls): params.extend(p.__args__) else: params.append(p) return tuple(params) def normalise_optional_params(parameters: Iterable[Any]) -> Tuple[Any, ...]: none_cls = type(None) return tuple(p for p in parameters if p is not none_cls) + (none_cls,) def evaluate_annotation( tp: Any, globals: Dict[str, Any], locals: Dict[str, Any], cache: Dict[str, Any], *, implicit_str: bool = True, ): if isinstance(tp, ForwardRef): tp = tp.__forward_arg__ # ForwardRefs always evaluate their internals implicit_str = True if implicit_str and isinstance(tp, str): if tp in cache: return cache[tp] evaluated = eval(tp, globals, locals) cache[tp] = evaluated return evaluate_annotation(evaluated, globals, locals, cache) if hasattr(tp, '__args__'): implicit_str = True is_literal = False args = tp.__args__ if not hasattr(tp, '__origin__'): if PY_310 and tp.__class__ is types.UnionType: # type: ignore converted = Union[args] # type: ignore return evaluate_annotation(converted, globals, locals, cache) return tp if tp.__origin__ is Union: try: if args.index(type(None)) != len(args) - 1: args = normalise_optional_params(tp.__args__) except ValueError: pass if tp.__origin__ is Literal: if not PY_310: args = flatten_literal_params(tp.__args__) implicit_str = False is_literal = True evaluated_args = tuple(evaluate_annotation(arg, globals, locals, cache, implicit_str=implicit_str) for arg in args) if is_literal and not all(isinstance(x, (str, int, bool, type(None))) for x in evaluated_args): raise TypeError('Literal arguments must be of type str, int, bool, or NoneType.') if evaluated_args == args: return tp try: return tp.copy_with(evaluated_args) except AttributeError: return tp.__origin__[evaluated_args] return tp def resolve_annotation( annotation: Any, globalns: Dict[str, Any], localns: Optional[Dict[str, Any]], cache: Optional[Dict[str, Any]], ) -> Any: if annotation is None: return type(None) if isinstance(annotation, str): annotation = ForwardRef(annotation) locals = globalns if localns is None else localns if cache is None: cache = {} return evaluate_annotation(annotation, globalns, locals, cache) TimestampStyle = Literal['f', 'F', 'd', 'D', 't', 'T', 'R'] 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 style is None: return f'<t:{int(dt.timestamp())}>' return f'<t:{int(dt.timestamp())}:{style}>'
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/utils.py
utils.py
from __future__ import annotations from typing import Type, TypeVar, Union, List, TYPE_CHECKING, Any, Union __all__ = ( 'AllowedMentions', ) if TYPE_CHECKING: from .types.message import AllowedMentions as AllowedMentionsPayload from .abc import Snowflake class _FakeBool: def __repr__(self): return 'True' def __eq__(self, other): return other is True def __bool__(self): return True default: Any = _FakeBool() A = TypeVar('A', bound='AllowedMentions') class AllowedMentions: """A class that represents what mentions are allowed in a message. This class can be set during :class:`Client` initialisation to apply to every message sent. It can also be applied on a per message basis via :meth:`abc.Messageable.send` for more fine-grained control. Attributes ------------ everyone: :class:`bool` Whether to allow everyone and here mentions. Defaults to ``True``. users: Union[:class:`bool`, List[:class:`abc.Snowflake`]] Controls the users being mentioned. If ``True`` (the default) then users are mentioned based on the message content. If ``False`` then users are not mentioned at all. If a list of :class:`abc.Snowflake` is given then only the users provided will be mentioned, provided those users are in the message content. roles: Union[:class:`bool`, List[:class:`abc.Snowflake`]] Controls the roles being mentioned. If ``True`` (the default) then roles are mentioned based on the message content. If ``False`` then roles are not mentioned at all. If a list of :class:`abc.Snowflake` is given then only the roles provided will be mentioned, provided those roles are in the message content. replied_user: :class:`bool` Whether to mention the author of the message being replied to. Defaults to ``True``. .. versionadded:: 1.6 """ __slots__ = ('everyone', 'users', 'roles', 'replied_user') def __init__( self, *, everyone: bool = default, users: Union[bool, List[Snowflake]] = default, roles: Union[bool, List[Snowflake]] = default, replied_user: bool = default, ): self.everyone = everyone self.users = users self.roles = roles self.replied_user = replied_user @classmethod def all(cls: Type[A]) -> A: """A factory method that returns a :class:`AllowedMentions` with all fields explicitly set to ``True`` .. versionadded:: 1.5 """ return cls(everyone=True, users=True, roles=True, replied_user=True) @classmethod def none(cls: Type[A]) -> A: """A factory method that returns a :class:`AllowedMentions` with all fields set to ``False`` .. versionadded:: 1.5 """ return cls(everyone=False, users=False, roles=False, replied_user=False) def to_dict(self) -> AllowedMentionsPayload: parse = [] data = {} if self.everyone: parse.append('everyone') if self.users == True: parse.append('users') elif self.users != False: data['users'] = [x.id for x in self.users] if self.roles == True: parse.append('roles') elif self.roles != False: data['roles'] = [x.id for x in self.roles] if self.replied_user: data['replied_user'] = True data['parse'] = parse return data # type: ignore def merge(self, other: AllowedMentions) -> AllowedMentions: # Creates a new AllowedMentions by merging from another one. # Merge is done by using the 'self' values unless explicitly # overridden by the 'other' values. everyone = self.everyone if other.everyone is default else other.everyone users = self.users if other.users is default else other.users roles = self.roles if other.roles is default else other.roles replied_user = self.replied_user if other.replied_user is default else other.replied_user return AllowedMentions(everyone=everyone, roles=roles, users=users, replied_user=replied_user) def __repr__(self) -> str: return ( f'{self.__class__.__name__}(everyone={self.everyone}, ' f'users={self.users}, roles={self.roles}, replied_user={self.replied_user})' )
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/mentions.py
mentions.py
from __future__ import annotations from typing import Any, Dict, List, Optional, Type, TypeVar, TYPE_CHECKING import discord.abc from .asset import Asset from .colour import Colour from .enums import DefaultAvatar from .flags import PublicUserFlags from .utils import snowflake_time, _bytes_to_base64_data, MISSING if TYPE_CHECKING: from datetime import datetime from .channel import DMChannel from .guild import Guild from .message import Message from .state import ConnectionState from .types.channel import DMChannel as DMChannelPayload from .types.user import User as UserPayload __all__ = ( 'User', 'ClientUser', ) BU = TypeVar('BU', bound='BaseUser') class _UserTag: __slots__ = () id: int class BaseUser(_UserTag): __slots__ = ( 'name', 'id', 'discriminator', '_avatar', '_banner', '_accent_colour', 'bot', 'system', '_public_flags', '_state', ) if TYPE_CHECKING: name: str id: int discriminator: str bot: bool system: bool _state: ConnectionState _avatar: Optional[str] _banner: Optional[str] _accent_colour: Optional[str] _public_flags: int def __init__(self, *, state: ConnectionState, data: UserPayload) -> None: self._state = state self._update(data) def __repr__(self) -> str: return ( f"<BaseUser id={self.id} name={self.name!r} discriminator={self.discriminator!r}" f" bot={self.bot} system={self.system}>" ) def __str__(self) -> str: return f'{self.name}#{self.discriminator}' 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: 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) @classmethod def _copy(cls: Type[BU], user: BU) -> BU: 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, 'discriminator': self.discriminator, 'bot': self.bot, } @property def public_flags(self) -> PublicUserFlags: """:class:`PublicUserFlags`: The publicly available flags the user has.""" return PublicUserFlags._from_value(self._public_flags) @property 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 @property def default_avatar(self) -> Asset: """:class:`Asset`: Returns the default avatar for a given user. This is calculated by the user's discriminator.""" return Asset._from_default_avatar(self._state, int(self.discriminator) % len(DefaultAvatar)) @property 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 @property 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) @property 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(self._accent_colour) @property 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 @property 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() @property 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 @property def mention(self) -> str: """:class:`str`: Returns a string that allows you to mention the given user.""" return f'<@{self.id}>' @property 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) @property 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 ClientUser(BaseUser): """Represents your 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. discriminator: :class:`str` The user's discriminator. This is given when the username has conflicts. 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). .. versionadded:: 1.3 verified: :class:`bool` Specifies if the user's email is verified. locale: Optional[:class:`str`] The IETF language tag used to identify the language the user is using. mfa_enabled: :class:`bool` Specifies if the user has MFA turned on and working. """ __slots__ = ('locale', '_flags', 'verified', 'mfa_enabled', '__weakref__') if TYPE_CHECKING: verified: bool locale: Optional[str] mfa_enabled: bool _flags: int def __init__(self, *, state: ConnectionState, data: UserPayload) -> None: super().__init__(state=state, data=data) def __repr__(self) -> str: return ( f'<ClientUser id={self.id} name={self.name!r} discriminator={self.discriminator!r}' f' bot={self.bot} verified={self.verified} mfa_enabled={self.mfa_enabled}>' ) def _update(self, data: UserPayload) -> None: super()._update(data) # There's actually an Optional[str] phone field as well but I won't use it self.verified = data.get('verified', False) self.locale = data.get('locale') self._flags = data.get('flags', 0) self.mfa_enabled = data.get('mfa_enabled', False) async def edit(self, *, username: str = MISSING, avatar: bytes = MISSING) -> ClientUser: """|coro| Edits the current profile of the client. .. note:: To upload an avatar, a :term:`py:bytes-like object` must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via ``open('some_filename', 'rb')`` and the :term:`py:bytes-like object` is given through the use of ``fp.read()``. The only image formats supported for uploading is JPEG and PNG. .. versionchanged:: 2.0 The edit is no longer in-place, instead the newly edited client user is returned. Parameters ----------- username: :class:`str` The new username you wish to change to. avatar: :class:`bytes` A :term:`py:bytes-like object` representing the image to upload. Could be ``None`` to denote no avatar. Raises ------ HTTPException Editing your profile failed. InvalidArgument Wrong image format passed for ``avatar``. Returns --------- :class:`ClientUser` The newly edited client user. """ payload: Dict[str, Any] = {} if username is not MISSING: payload['username'] = username if avatar is not MISSING: payload['avatar'] = _bytes_to_base64_data(avatar) data: UserPayload = await self._state.http.edit_profile(payload) return ClientUser(state=self._state, data=data) class User(BaseUser, discord.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. discriminator: :class:`str` The user's discriminator. This is given when the username has conflicts. 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: 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} discriminator={self.discriminator!r} bot={self.bot}>' def __del__(self) -> None: try: if self._stored: self._state.deref_user(self.id) except Exception: pass @classmethod def _copy(cls, user: User): self = super()._copy(user) self._stored = False return self async def _get_channel(self) -> DMChannel: ch = await self.create_dm() return ch @property 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) @property 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)
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/user.py
user.py
from __future__ import annotations from typing import Any, TYPE_CHECKING, Union, Optional from .iterators import ReactionIterator __all__ = ( 'Reaction', ) if TYPE_CHECKING: from .types.message import Reaction as ReactionPayload from .message import Message from .partial_emoji import PartialEmoji from .emoji import Emoji from .abc import Snowflake class Reaction: """Represents a reaction to a message. Depending on the way this object was created, some of the attributes can have a value of ``None``. .. container:: operations .. describe:: x == y Checks if two reactions are equal. This works by checking if the emoji is the same. So two messages with the same reaction will be considered "equal". .. describe:: x != y Checks if two reactions are not equal. .. describe:: hash(x) Returns the reaction's hash. .. describe:: str(x) Returns the string form of the reaction's emoji. Attributes ----------- emoji: Union[:class:`Emoji`, :class:`PartialEmoji`, :class:`str`] The reaction emoji. May be a custom emoji, or a unicode emoji. count: :class:`int` Number of times this reaction was made me: :class:`bool` If the user sent this reaction. message: :class:`Message` Message this reaction is for. """ __slots__ = ('message', 'count', 'emoji', 'me') def __init__(self, *, message: Message, data: ReactionPayload, emoji: Optional[Union[PartialEmoji, Emoji, str]] = None): self.message: Message = message self.emoji: Union[PartialEmoji, Emoji, str] = emoji or message._state.get_reaction_emoji(data['emoji']) self.count: int = data.get('count', 1) self.me: bool = data.get('me') # TODO: typeguard def is_custom_emoji(self) -> bool: """:class:`bool`: If this is a custom emoji.""" return not isinstance(self.emoji, str) def __eq__(self, other: Any) -> bool: return isinstance(other, self.__class__) and other.emoji == self.emoji def __ne__(self, other: Any) -> bool: if isinstance(other, self.__class__): return other.emoji != self.emoji return True def __hash__(self) -> int: return hash(self.emoji) def __str__(self) -> str: return str(self.emoji) def __repr__(self) -> str: return f'<Reaction emoji={self.emoji!r} me={self.me} count={self.count}>' async def remove(self, user: Snowflake) -> None: """|coro| Remove the reaction by the provided :class:`User` from the message. If the reaction is not your own (i.e. ``user`` parameter is not you) then the :attr:`~Permissions.manage_messages` permission is needed. The ``user`` parameter must represent a user or member and meet the :class:`abc.Snowflake` abc. Parameters ----------- user: :class:`abc.Snowflake` The user or member from which to remove the reaction. Raises ------- HTTPException Removing the reaction failed. Forbidden You do not have the proper permissions to remove the reaction. NotFound The user you specified, or the reaction's message was not found. """ await self.message.remove_reaction(self.emoji, user) async def clear(self) -> None: """|coro| Clears this reaction from the message. You need the :attr:`~Permissions.manage_messages` permission to use this. .. versionadded:: 1.3 Raises -------- HTTPException Clearing the reaction failed. Forbidden You do not have the proper permissions to clear the reaction. NotFound The emoji you specified was not found. InvalidArgument The emoji parameter is invalid. """ await self.message.clear_reaction(self.emoji) def users(self, *, limit: Optional[int] = None, after: Optional[Snowflake] = None) -> ReactionIterator: """Returns an :class:`AsyncIterator` representing the users that have reacted to the message. The ``after`` parameter must represent a member and meet the :class:`abc.Snowflake` abc. Examples --------- Usage :: # I do not actually recommend doing this. async for user in reaction.users(): await channel.send(f'{user} has reacted with {reaction.emoji}!') Flattening into a list: :: users = await reaction.users().flatten() # users is now a list of User... winner = random.choice(users) await channel.send(f'{winner} has won the raffle.') Parameters ------------ limit: Optional[:class:`int`] The maximum number of results to return. If not provided, returns all the users who reacted to the message. after: Optional[:class:`abc.Snowflake`] For pagination, reactions are sorted by member. Raises -------- HTTPException Getting the users for the reaction failed. Yields -------- Union[:class:`User`, :class:`Member`] The member (if retrievable) or the user that has reacted to this message. The case where it can be a :class:`Member` is in a guild message context. Sometimes it can be a :class:`User` if the member has left the guild. """ if not isinstance(self.emoji, str): emoji = f'{self.emoji.name}:{self.emoji.id}' else: emoji = self.emoji if limit is None: limit = self.count return ReactionIterator(self.message, emoji, limit, after)
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/reaction.py
reaction.py
from __future__ import annotations import asyncio import datetime from typing import Awaitable, TYPE_CHECKING, TypeVar, Optional, Any, Callable, Union, List, AsyncIterator from .errors import NoMoreItems from .utils import snowflake_time, time_snowflake, maybe_coroutine from .object import Object from .audit_logs import AuditLogEntry __all__ = ( 'ReactionIterator', 'HistoryIterator', 'AuditLogIterator', 'GuildIterator', 'MemberIterator', ) if TYPE_CHECKING: from .types.audit_log import ( AuditLog as AuditLogPayload, ) from .types.guild import ( Guild as GuildPayload, ) from .types.message import ( Message as MessagePayload, ) from .types.user import ( PartialUser as PartialUserPayload, ) from .types.threads import ( Thread as ThreadPayload, ) from .member import Member from .user import User from .message import Message from .audit_logs import AuditLogEntry from .guild import Guild from .threads import Thread from .abc import Snowflake T = TypeVar('T') OT = TypeVar('OT') _Func = Callable[[T], Union[OT, Awaitable[OT]]] OLDEST_OBJECT = Object(id=0) class _AsyncIterator(AsyncIterator[T]): __slots__ = () async def next(self) -> T: raise NotImplementedError def get(self, **attrs: Any) -> Awaitable[Optional[T]]: def predicate(elem: T): for attr, val in attrs.items(): nested = attr.split('__') obj = elem for attribute in nested: obj = getattr(obj, attribute) if obj != val: return False return True return self.find(predicate) async def find(self, predicate: _Func[T, bool]) -> Optional[T]: while True: try: elem = await self.next() except NoMoreItems: return None ret = await maybe_coroutine(predicate, elem) if ret: return elem def chunk(self, max_size: int) -> _ChunkedAsyncIterator[T]: if max_size <= 0: raise ValueError('async iterator chunk sizes must be greater than 0.') return _ChunkedAsyncIterator(self, max_size) def map(self, func: _Func[T, OT]) -> _MappedAsyncIterator[OT]: return _MappedAsyncIterator(self, func) def filter(self, predicate: _Func[T, bool]) -> _FilteredAsyncIterator[T]: return _FilteredAsyncIterator(self, predicate) async def flatten(self) -> List[T]: return [element async for element in self] async def __anext__(self) -> T: try: return await self.next() except NoMoreItems: raise StopAsyncIteration() def _identity(x): return x class _ChunkedAsyncIterator(_AsyncIterator[List[T]]): def __init__(self, iterator, max_size): self.iterator = iterator self.max_size = max_size async def next(self) -> List[T]: ret: List[T] = [] n = 0 while n < self.max_size: try: item = await self.iterator.next() except NoMoreItems: if ret: return ret raise else: ret.append(item) n += 1 return ret class _MappedAsyncIterator(_AsyncIterator[T]): def __init__(self, iterator, func): self.iterator = iterator self.func = func async def next(self) -> T: # this raises NoMoreItems and will propagate appropriately item = await self.iterator.next() return await maybe_coroutine(self.func, item) class _FilteredAsyncIterator(_AsyncIterator[T]): def __init__(self, iterator, predicate): self.iterator = iterator if predicate is None: predicate = _identity self.predicate = predicate async def next(self) -> T: getter = self.iterator.next pred = self.predicate while True: # propagate NoMoreItems similar to _MappedAsyncIterator item = await getter() ret = await maybe_coroutine(pred, item) if ret: return item class ReactionIterator(_AsyncIterator[Union['User', 'Member']]): def __init__(self, message, emoji, limit=100, after=None): self.message = message self.limit = limit self.after = after state = message._state self.getter = state.http.get_reaction_users self.state = state self.emoji = emoji self.guild = message.guild self.channel_id = message.channel.id self.users = asyncio.Queue() async def next(self) -> Union[User, Member]: if self.users.empty(): await self.fill_users() try: return self.users.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() async def fill_users(self): # this is a hack because >circular imports< from .user import User if self.limit > 0: retrieve = self.limit if self.limit <= 100 else 100 after = self.after.id if self.after else None data: List[PartialUserPayload] = await self.getter( self.channel_id, self.message.id, self.emoji, retrieve, after=after ) if data: self.limit -= retrieve self.after = Object(id=int(data[-1]['id'])) if self.guild is None or isinstance(self.guild, Object): for element in reversed(data): await self.users.put(User(state=self.state, data=element)) else: for element in reversed(data): member_id = int(element['id']) member = self.guild.get_member(member_id) if member is not None: await self.users.put(member) else: await self.users.put(User(state=self.state, data=element)) class HistoryIterator(_AsyncIterator['Message']): """Iterator for receiving a channel's message history. The messages endpoint has two behaviours we care about here: If ``before`` is specified, the messages endpoint returns the `limit` newest messages before ``before``, sorted with newest first. For filling over 100 messages, update the ``before`` parameter to the oldest message received. Messages will be returned in order by time. If ``after`` is specified, it returns the ``limit`` oldest messages after ``after``, sorted with newest first. For filling over 100 messages, update the ``after`` parameter to the newest message received. If messages are not reversed, they will be out of order (99-0, 199-100, so on) A note that if both ``before`` and ``after`` are specified, ``before`` is ignored by the messages endpoint. Parameters ----------- messageable: :class:`abc.Messageable` Messageable class to retrieve message history from. limit: :class:`int` Maximum number of messages to retrieve before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Message before which all messages must be. after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Message after which all messages must be. around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Message around which all messages must be. Limit max 101. Note that if limit is an even number, this will return at most limit+1 messages. oldest_first: Optional[:class:`bool`] If set to ``True``, return messages in oldest->newest order. Defaults to ``True`` if `after` is specified, otherwise ``False``. """ def __init__(self, messageable, limit, before=None, after=None, around=None, oldest_first=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) if isinstance(around, datetime.datetime): around = Object(id=time_snowflake(around)) if oldest_first is None: self.reverse = after is not None else: self.reverse = oldest_first self.messageable = messageable self.limit = limit self.before = before self.after = after or OLDEST_OBJECT self.around = around self._filter = None # message dict -> bool self.state = self.messageable._state self.logs_from = self.state.http.logs_from self.messages = asyncio.Queue() if self.around: if self.limit is None: raise ValueError('history does not support around with limit=None') if self.limit > 101: raise ValueError("history max limit 101 when specifying around parameter") elif self.limit == 101: self.limit = 100 # Thanks discord self._retrieve_messages = self._retrieve_messages_around_strategy # type: ignore if self.before and self.after: self._filter = lambda m: self.after.id < int(m['id']) < self.before.id elif self.before: self._filter = lambda m: int(m['id']) < self.before.id elif self.after: self._filter = lambda m: self.after.id < int(m['id']) else: if self.reverse: self._retrieve_messages = self._retrieve_messages_after_strategy # type: ignore if self.before: self._filter = lambda m: int(m['id']) < self.before.id else: self._retrieve_messages = self._retrieve_messages_before_strategy # type: ignore if self.after and self.after != OLDEST_OBJECT: self._filter = lambda m: int(m['id']) > self.after.id async def next(self) -> Message: if self.messages.empty(): await self.fill_messages() try: return self.messages.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 async def fill_messages(self): if not hasattr(self, 'channel'): # do the required set up channel = await self.messageable._get_channel() self.channel = channel if self._get_retrieve(): data = await self._retrieve_messages(self.retrieve) if len(data) < 100: self.limit = 0 # terminate the infinite loop if self.reverse: data = reversed(data) if self._filter: data = filter(self._filter, data) channel = self.channel for element in data: await self.messages.put(self.state.create_message(channel=channel, data=element)) async def _retrieve_messages(self, retrieve) -> List[Message]: """Retrieve messages and update next parameters.""" raise NotImplementedError async def _retrieve_messages_before_strategy(self, retrieve): """Retrieve messages using before parameter.""" before = self.before.id if self.before else None data: List[MessagePayload] = await self.logs_from(self.channel.id, retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data async def _retrieve_messages_after_strategy(self, retrieve): """Retrieve messages using after parameter.""" after = self.after.id if self.after else None data: List[MessagePayload] = await self.logs_from(self.channel.id, retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data async def _retrieve_messages_around_strategy(self, retrieve): """Retrieve messages using around parameter.""" if self.around: around = self.around.id if self.around else None data: List[MessagePayload] = await self.logs_from(self.channel.id, retrieve, around=around) self.around = None return data return [] class AuditLogIterator(_AsyncIterator['AuditLogEntry']): def __init__(self, guild, limit=None, before=None, after=None, oldest_first=None, user_id=None, action_type=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) if oldest_first is None: self.reverse = after is not None else: self.reverse = oldest_first self.guild = guild self.loop = guild._state.loop self.request = guild._state.http.get_audit_logs self.limit = limit self.before = before self.user_id = user_id self.action_type = action_type self.after = OLDEST_OBJECT self._users = {} self._state = guild._state self._filter = None # entry dict -> bool self.entries = asyncio.Queue() if self.reverse: self._strategy = self._after_strategy if self.before: self._filter = lambda m: int(m['id']) < self.before.id else: self._strategy = self._before_strategy if self.after and self.after != OLDEST_OBJECT: self._filter = lambda m: int(m['id']) > self.after.id async def _before_strategy(self, retrieve): before = self.before.id if self.before else None data: AuditLogPayload = await self.request( self.guild.id, limit=retrieve, user_id=self.user_id, action_type=self.action_type, before=before ) entries = data.get('audit_log_entries', []) if len(data) and entries: if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(entries[-1]['id'])) return data.get('users', []), entries async def _after_strategy(self, retrieve): after = self.after.id if self.after else None data: AuditLogPayload = await self.request( self.guild.id, limit=retrieve, user_id=self.user_id, action_type=self.action_type, after=after ) entries = data.get('audit_log_entries', []) if len(data) and entries: if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(entries[0]['id'])) return data.get('users', []), entries async def next(self) -> AuditLogEntry: if self.entries.empty(): await self._fill() try: return self.entries.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 async def _fill(self): from .user import User if self._get_retrieve(): users, data = await self._strategy(self.retrieve) if len(data) < 100: self.limit = 0 # terminate the infinite loop if self.reverse: data = reversed(data) if self._filter: data = filter(self._filter, data) for user in users: u = User(data=user, state=self._state) self._users[u.id] = u for element in data: # TODO: remove this if statement later if element['action_type'] is None: continue await self.entries.put(AuditLogEntry(data=element, users=self._users, guild=self.guild)) class GuildIterator(_AsyncIterator['Guild']): """Iterator for receiving the client's guilds. The guilds endpoint has the same two behaviours as described in :class:`HistoryIterator`: If ``before`` is specified, the guilds endpoint returns the ``limit`` newest guilds before ``before``, sorted with newest first. For filling over 100 guilds, update the ``before`` parameter to the oldest guild received. Guilds will be returned in order by time. If `after` is specified, it returns the ``limit`` oldest guilds after ``after``, sorted with newest first. For filling over 100 guilds, update the ``after`` parameter to the newest guild received, If guilds are not reversed, they will be out of order (99-0, 199-100, so on) Not that if both ``before`` and ``after`` are specified, ``before`` is ignored by the guilds endpoint. Parameters ----------- bot: :class:`discord.Client` The client to retrieve the guilds from. limit: :class:`int` Maximum number of guilds to retrieve. before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Object before which all guilds must be. after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Object after which all guilds must be. """ def __init__(self, bot, limit, before=None, after=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) self.bot = bot self.limit = limit self.before = before self.after = after self._filter = None self.state = self.bot._connection self.get_guilds = self.bot.http.get_guilds self.guilds = asyncio.Queue() if self.before and self.after: self._retrieve_guilds = self._retrieve_guilds_before_strategy # type: ignore self._filter = lambda m: int(m['id']) > self.after.id elif self.after: self._retrieve_guilds = self._retrieve_guilds_after_strategy # type: ignore else: self._retrieve_guilds = self._retrieve_guilds_before_strategy # type: ignore async def next(self) -> Guild: if self.guilds.empty(): await self.fill_guilds() try: return self.guilds.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 def create_guild(self, data): from .guild import Guild return Guild(state=self.state, data=data) async def fill_guilds(self): if self._get_retrieve(): data = await self._retrieve_guilds(self.retrieve) if self.limit is None or len(data) < 100: self.limit = 0 if self._filter: data = filter(self._filter, data) for element in data: await self.guilds.put(self.create_guild(element)) async def _retrieve_guilds(self, retrieve) -> List[Guild]: """Retrieve guilds and update next parameters.""" raise NotImplementedError async def _retrieve_guilds_before_strategy(self, retrieve): """Retrieve guilds using before parameter.""" before = self.before.id if self.before else None data: List[GuildPayload] = await self.get_guilds(retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data async def _retrieve_guilds_after_strategy(self, retrieve): """Retrieve guilds using after parameter.""" after = self.after.id if self.after else None data: List[GuildPayload] = await self.get_guilds(retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data class MemberIterator(_AsyncIterator['Member']): def __init__(self, guild, limit=1000, after=None): if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) self.guild = guild self.limit = limit self.after = after or OLDEST_OBJECT self.state = self.guild._state self.get_members = self.state.http.get_members self.members = asyncio.Queue() async def next(self) -> Member: if self.members.empty(): await self.fill_members() try: return self.members.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 1000: r = 1000 else: r = l self.retrieve = r return r > 0 async def fill_members(self): if self._get_retrieve(): after = self.after.id if self.after else None data = await self.get_members(self.guild.id, self.retrieve, after) if not data: # no data, terminate return if len(data) < 1000: self.limit = 0 # terminate loop self.after = Object(id=int(data[-1]['user']['id'])) for element in reversed(data): await self.members.put(self.create_member(element)) def create_member(self, data): from .member import Member return Member(data=data, guild=self.guild, state=self.state) class ArchivedThreadIterator(_AsyncIterator['Thread']): def __init__( self, channel_id: int, guild: Guild, limit: Optional[int], joined: bool, private: bool, before: Optional[Union[Snowflake, datetime.datetime]] = None, ): self.channel_id = channel_id self.guild = guild self.limit = limit self.joined = joined self.private = private self.http = guild._state.http if joined and not private: raise ValueError('Cannot iterate over joined public archived threads') self.before: Optional[str] if before is None: self.before = None elif isinstance(before, datetime.datetime): if joined: self.before = str(time_snowflake(before, high=False)) else: self.before = before.isoformat() else: if joined: self.before = str(before.id) else: self.before = snowflake_time(before.id).isoformat() self.update_before: Callable[[ThreadPayload], str] = self.get_archive_timestamp if joined: self.endpoint = self.http.get_joined_private_archived_threads self.update_before = self.get_thread_id elif private: self.endpoint = self.http.get_private_archived_threads else: self.endpoint = self.http.get_public_archived_threads self.queue: asyncio.Queue[Thread] = asyncio.Queue() self.has_more: bool = True async def next(self) -> Thread: if self.queue.empty(): await self.fill_queue() try: return self.queue.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() @staticmethod def get_archive_timestamp(data: ThreadPayload) -> str: return data['thread_metadata']['archive_timestamp'] @staticmethod def get_thread_id(data: ThreadPayload) -> str: return data['id'] # type: ignore async def fill_queue(self) -> None: if not self.has_more: raise NoMoreItems() limit = 50 if self.limit is None else max(self.limit, 50) data = await self.endpoint(self.channel_id, before=self.before, limit=limit) # This stuff is obviously WIP because 'members' is always empty threads: List[ThreadPayload] = data.get('threads', []) for d in reversed(threads): self.queue.put_nowait(self.create_thread(d)) self.has_more = data.get('has_more', False) if self.limit is not None: self.limit -= len(threads) if self.limit <= 0: self.has_more = False if self.has_more: self.before = self.update_before(threads[-1]) def create_thread(self, data: ThreadPayload) -> Thread: from .threads import Thread return Thread(guild=self.guild, state=self.guild._state, data=data)
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/iterators.py
iterators.py
from __future__ import annotations from typing import Any, Optional, TYPE_CHECKING from .utils import parse_time, _get_as_snowflake, _bytes_to_base64_data, MISSING from .enums import VoiceRegion from .guild import Guild __all__ = ( 'Template', ) if TYPE_CHECKING: import datetime from .types.template import Template as TemplatePayload from .state import ConnectionState from .user import User class _FriendlyHttpAttributeErrorHelper: __slots__ = () def __getattr__(self, attr): raise AttributeError('PartialTemplateState does not support http methods.') class _PartialTemplateState: def __init__(self, *, state): self.__state = state self.http = _FriendlyHttpAttributeErrorHelper() @property def shard_count(self): return self.__state.shard_count @property def user(self): return self.__state.user @property def self_id(self): return self.__state.user.id @property def member_cache_flags(self): return self.__state.member_cache_flags def store_emoji(self, guild, packet): return None def _get_voice_client(self, id): return None def _get_message(self, id): return None def _get_guild(self, id): return self.__state._get_guild(id) async def query_members(self, **kwargs: Any): return [] def __getattr__(self, attr): raise AttributeError(f'PartialTemplateState does not support {attr!r}.') class Template: """Represents a Discord template. .. versionadded:: 1.4 Attributes ----------- code: :class:`str` The template code. uses: :class:`int` How many times the template has been used. name: :class:`str` The name of the template. description: :class:`str` The description of the template. creator: :class:`User` The creator of the template. created_at: :class:`datetime.datetime` An aware datetime in UTC representing when the template was created. updated_at: :class:`datetime.datetime` An aware datetime in UTC representing when the template was last updated. This is referred to as "last synced" in the official Discord client. source_guild: :class:`Guild` The source guild. is_dirty: Optional[:class:`bool`] Whether the template has unsynced changes. .. versionadded:: 2.0 """ __slots__ = ( 'code', 'uses', 'name', 'description', 'creator', 'created_at', 'updated_at', 'source_guild', 'is_dirty', '_state', ) def __init__(self, *, state: ConnectionState, data: TemplatePayload) -> None: self._state = state self._store(data) def _store(self, data: TemplatePayload) -> None: self.code: str = data['code'] self.uses: int = data['usage_count'] self.name: str = data['name'] self.description: Optional[str] = data['description'] creator_data = data.get('creator') self.creator: Optional[User] = None if creator_data is None else self._state.create_user(creator_data) self.created_at: Optional[datetime.datetime] = parse_time(data.get('created_at')) self.updated_at: Optional[datetime.datetime] = parse_time(data.get('updated_at')) guild_id = int(data['source_guild_id']) guild: Optional[Guild] = self._state._get_guild(guild_id) self.source_guild: Guild if guild is None: source_serialised = data['serialized_source_guild'] source_serialised['id'] = guild_id state = _PartialTemplateState(state=self._state) # Guild expects a ConnectionState, we're passing a _PartialTemplateState self.source_guild = Guild(data=source_serialised, state=state) # type: ignore else: self.source_guild = guild self.is_dirty: Optional[bool] = data.get('is_dirty', None) def __repr__(self) -> str: return ( f'<Template code={self.code!r} uses={self.uses} name={self.name!r}' f' creator={self.creator!r} source_guild={self.source_guild!r} is_dirty={self.is_dirty}>' ) async def create_guild(self, name: str, region: Optional[VoiceRegion] = None, icon: Any = None) -> Guild: """|coro| Creates a :class:`.Guild` using the template. Bot accounts in more than 10 guilds are not allowed to create guilds. Parameters ---------- name: :class:`str` The name of the guild. region: :class:`.VoiceRegion` The region for the voice communication server. Defaults to :attr:`.VoiceRegion.us_west`. icon: :class:`bytes` The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit` for more details on what is expected. Raises ------ HTTPException Guild creation failed. InvalidArgument Invalid icon image format given. Must be PNG or JPG. Returns ------- :class:`.Guild` The guild created. This is not the same guild that is added to cache. """ if icon is not None: icon = _bytes_to_base64_data(icon) region = region or VoiceRegion.us_west region_value = region.value data = await self._state.http.create_from_template(self.code, name, region_value, icon) return Guild(data=data, state=self._state) async def sync(self) -> Template: """|coro| Sync the template to the guild's current state. You must have the :attr:`~Permissions.manage_guild` permission in the source guild to do this. .. versionadded:: 1.7 .. versionchanged:: 2.0 The template is no longer edited in-place, instead it is returned. Raises ------- HTTPException Editing the template failed. Forbidden You don't have permissions to edit the template. NotFound This template does not exist. Returns -------- :class:`Template` The newly edited template. """ data = await self._state.http.sync_template(self.source_guild.id, self.code) return Template(state=self._state, data=data) async def edit( self, *, name: str = MISSING, description: Optional[str] = MISSING, ) -> Template: """|coro| Edit the template metadata. You must have the :attr:`~Permissions.manage_guild` permission in the source guild to do this. .. versionadded:: 1.7 .. versionchanged:: 2.0 The template is no longer edited in-place, instead it is returned. Parameters ------------ name: :class:`str` The template's new name. description: Optional[:class:`str`] The template's new description. Raises ------- HTTPException Editing the template failed. Forbidden You don't have permissions to edit the template. NotFound This template does not exist. Returns -------- :class:`Template` The newly edited template. """ payload = {} if name is not MISSING: payload['name'] = name if description is not MISSING: payload['description'] = description data = await self._state.http.edit_template(self.source_guild.id, self.code, payload) return Template(state=self._state, data=data) async def delete(self) -> None: """|coro| Delete the template. You must have the :attr:`~Permissions.manage_guild` permission in the source guild to do this. .. versionadded:: 1.7 Raises ------- HTTPException Editing the template failed. Forbidden You don't have permissions to edit the template. NotFound This template does not exist. """ await self._state.http.delete_template(self.source_guild.id, self.code) @property def url(self) -> str: """:class:`str`: The template url. .. versionadded:: 2.0 """ return f'https://discord.new/{self.code}'
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/template.py
template.py
from __future__ import annotations import asyncio from collections import deque, OrderedDict import copy import datetime import itertools import logging from typing import Dict, Optional, TYPE_CHECKING, Union, Callable, Any, List, TypeVar, Coroutine, Sequence, Tuple, Deque import inspect import os from .guild import Guild from .activity import BaseActivity from .user import User, ClientUser from .emoji import Emoji from .mentions import AllowedMentions from .partial_emoji import PartialEmoji from .message import Message from .channel import * from .channel import _channel_factory from .raw_models import * from .member import Member from .role import Role from .enums import ChannelType, try_enum, Status from . import utils from .flags import ApplicationFlags, Intents, MemberCacheFlags from .object import Object from .invite import Invite from .integrations import _integration_factory from .interactions import Interaction from .ui.view import ViewStore, View from .stage_instance import StageInstance from .threads import Thread, ThreadMember from .sticker import GuildSticker if TYPE_CHECKING: from .abc import PrivateChannel from .message import MessageableChannel from .guild import GuildChannel, VocalGuildChannel from .http import HTTPClient from .voice_client import VoiceProtocol from .client import Client from .gateway import DiscordWebSocket from .types.activity import Activity as ActivityPayload from .types.channel import DMChannel as DMChannelPayload from .types.user import User as UserPayload from .types.emoji import Emoji as EmojiPayload from .types.sticker import GuildSticker as GuildStickerPayload from .types.guild import Guild as GuildPayload from .types.message import Message as MessagePayload T = TypeVar('T') CS = TypeVar('CS', bound='ConnectionState') Channel = Union[GuildChannel, VocalGuildChannel, PrivateChannel, PartialMessageable] class ChunkRequest: def __init__( self, guild_id: int, loop: asyncio.AbstractEventLoop, resolver: Callable[[int], Any], *, cache: bool = True, ) -> None: self.guild_id: int = guild_id self.resolver: Callable[[int], Any] = resolver self.loop: asyncio.AbstractEventLoop = loop self.cache: bool = cache self.nonce: str = os.urandom(16).hex() self.buffer: List[Member] = [] self.waiters: List[asyncio.Future[List[Member]]] = [] def add_members(self, members: List[Member]) -> None: self.buffer.extend(members) if self.cache: guild = self.resolver(self.guild_id) if guild is None: return for member in members: existing = guild.get_member(member.id) if existing is None or existing.joined_at is None: guild._add_member(member) async def wait(self) -> List[Member]: future = self.loop.create_future() self.waiters.append(future) try: return await future finally: self.waiters.remove(future) def get_future(self) -> asyncio.Future[List[Member]]: future = self.loop.create_future() self.waiters.append(future) return future def done(self) -> None: for future in self.waiters: if not future.done(): future.set_result(self.buffer) _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) 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, **options: Any, ) -> None: self.loop: asyncio.AbstractEventLoop = loop self.http: HTTPClient = http self.max_messages: Optional[int] = options.get('max_messages', 1000) 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] = utils._get_as_snowflake(options, 'application_id') self.heartbeat_timeout: float = options.get('heartbeat_timeout', 60.0) self.guild_ready_timeout: float = options.get('guild_ready_timeout', 2.0) if self.guild_ready_timeout < 0: raise ValueError('guild_ready_timeout cannot be negative') allowed_mentions = options.get('allowed_mentions') 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] = {} activity = options.get('activity', None) if activity: if not isinstance(activity, BaseActivity): raise TypeError('activity parameter must derive from BaseActivity.') activity = activity.to_dict() status = options.get('status', None) if status: if status is Status.offline: status = 'invisible' else: status = str(status) intents = options.get('intents', None) if intents is not None: if not isinstance(intents, Intents): raise TypeError(f'intents parameter must be Intent not {type(intents)!r}') else: intents = Intents.default() if not intents.guilds: _log.warning('Guilds intent seems to be disabled. This may cause state related issues.') self._chunk_guilds: bool = options.get('chunk_guilds_at_startup', intents.members) # 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.') cache_flags = options.get('member_cache_flags', None) if cache_flags is None: cache_flags = MemberCacheFlags.from_intents(intents) else: if not isinstance(cache_flags, MemberCacheFlags): raise TypeError(f'member_cache_flags parameter must be MemberCacheFlags not {type(cache_flags)!r}') cache_flags._verify_intents(intents) self.member_cache_flags: MemberCacheFlags = cache_flags self._activity: Optional[ActivityPayload] = activity self._status: Optional[str] = status self._intents: Intents = intents if not intents.members or cache_flags._empty: self.store_user = self.create_user # type: ignore self.deref_user = self.deref_user_no_intents # type: ignore 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) -> 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 discernable 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] = {} if views: self._view_store: ViewStore = ViewStore(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) @property def self_id(self) -> Optional[int]: u = self.user return u.id if u else None @property def intents(self) -> Intents: ret = Intents.none() ret.value = self._intents.value return ret @property 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: 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 prevent_view_updates_for(self, message_id: int) -> Optional[View]: return self._view_store.remove_message_tracking(message_id) @property def persistent_views(self) -> Sequence[View]: return self._view_store.persistent_views @property 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 @property def emojis(self) -> List[Emoji]: return list(self._emojis.values()) @property 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 @property 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 = DMChannel._from_message(self, channel_id) guild = None else: channel = guild and guild._resolve_channel(channel_id) return channel or PartialMessageable(state=self, id=channel_id), guild 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: str, limit: int, user_ids: List[int], cache: bool, presences: bool): guild_id = guild.id ws = self._get_websocket(guild_id) if ws is None: 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)) else: if 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 try: del self._ready_state except AttributeError: pass # already been deleted somehow 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']) # type: ignore 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 or Thread if channel and channel.__class__ in (TextChannel, Thread): 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 = Interaction(data=data, state=self) 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) 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, ch_type = _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: 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) # type: ignore 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) try: guild._member_count += 1 except AttributeError: pass 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: try: guild._member_count -= 1 except AttributeError: pass user_id = int(data['user']['id']) member = guild.get_member(user_id) if member is not None: guild._remove_member(member) # type: ignore self.dispatch('member_remove', member) else: _log.debug('GUILD_MEMBER_REMOVE referencing an unknown guild ID: %s. Discarding.', data['guild_id']) 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 won't be None here guild.emojis = tuple(map(lambda d: self.store_emoji(guild, d), data['emojis'])) # type: ignore 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 won't be None here guild.stickers = tuple(map(lambda d: self.store_sticker(guild, d), data['stickers'])) # type: ignore 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=True, cache=None): cache = cache or 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): 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): asyncio.create_task(self._chunk_and_dispatch(guild, unavailable)) 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) asyncio.create_task(logging_coroutine(coro, info='Voice Protocol voice state update handler')) member, before, after = guild._update_voice_state(data, channel_id) # type: ignore 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) # type: ignore 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) asyncio.create_task(logging_coroutine(coro, info='Voice Protocol voice server update handler')) def parse_typing_start(self, data) -> None: channel, guild = self._get_guild_channel(data) if channel is not None: member = None user_id = utils._get_as_snowflake(data, 'user_id') if isinstance(channel, DMChannel): member = channel.recipient elif isinstance(channel, (Thread, TextChannel)) and guild is not None: # user_id won't be None member = guild.get_member(user_id) # type: ignore if member is None: member_data = data.get('member') if member_data: member = Member(data=member_data, state=self, guild=guild) elif isinstance(channel, GroupChannel): member = utils.find(lambda x: x.id == user_id, channel.recipients) if member is not None: timestamp = datetime.datetime.fromtimestamp(data.get('timestamp'), tz=datetime.timezone.utc) self.dispatch('typing', channel, member, timestamp) 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 def create_message( self, *, channel: Union[TextChannel, Thread, DMChannel, GroupChannel, PartialMessageable], data: MessagePayload ) -> Message: return Message(state=self, channel=channel, data=data) class AutoShardedConnectionState(ConnectionState): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.shard_ids: Union[List[int], range] = [] self.shards_launched: asyncio.Event = asyncio.Event() def _update_message_references(self) -> None: # self._messages won't be None when this is called for msg in self._messages: # type: ignore if not msg.guild: continue new_guild = self._get_guild(msg.guild.id) if new_guild is not None and new_guild is not msg.guild: channel_id = msg.channel.id channel = new_guild._resolve_channel(channel_id) or Object(id=channel_id) # channel will either be a TextChannel, Thread or Object msg._rebind_cached_references(new_guild, channel) # type: ignore async def chunker( self, guild_id: int, query: str = '', limit: int = 0, presences: bool = False, *, shard_id: Optional[int] = None, nonce: Optional[str] = None, ) -> None: ws = self._get_websocket(guild_id, shard_id=shard_id) await ws.request_chunks(guild_id, query=query, limit=limit, presences=presences, nonce=nonce) async def _delay_ready(self) -> None: await self.shards_launched.wait() processed = [] max_concurrency = len(self.shard_ids) * 2 current_bucket = [] 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): _log.debug('Guild ID %d requires chunking, will be done in the background.', guild.id) if len(current_bucket) >= max_concurrency: try: await utils.sane_wait_for(current_bucket, timeout=max_concurrency * 70.0) except asyncio.TimeoutError: fmt = 'Shard ID %s failed to wait for chunks from a sub-bucket with length %d' _log.warning(fmt, guild.shard_id, len(current_bucket)) finally: current_bucket = [] # Chunk the guild in the background while we wait for GUILD_CREATE streaming future = asyncio.ensure_future(self.chunk_guild(guild)) current_bucket.append(future) else: future = self.loop.create_future() future.set_result([]) processed.append((guild, future)) guilds = sorted(processed, key=lambda g: g[0].shard_id) for shard_id, info in itertools.groupby(guilds, key=lambda g: g[0].shard_id): children, futures = zip(*info) # 110 reqs/minute w/ 1 req/guild plus some buffer timeout = 61 * (len(children) / 110) try: await utils.sane_wait_for(futures, timeout=timeout) except asyncio.TimeoutError: _log.warning( 'Shard ID %s failed to wait for chunks (timeout=%.2f) for %d guilds', shard_id, timeout, len(guilds) ) for guild in children: if guild.unavailable is False: self.dispatch('guild_available', guild) else: self.dispatch('guild_join', guild) self.dispatch('shard_ready', shard_id) # remove the state try: del self._ready_state except AttributeError: pass # already been deleted somehow # regular users cannot shard so we won't worry about it here. # clear the current task self._ready_task = None # dispatch the event self.call_handlers('ready') self.dispatch('ready') def parse_ready(self, data) -> None: if not hasattr(self, '_ready_state'): self._ready_state = asyncio.Queue() self.user = user = ClientUser(state=self, data=data['user']) # self._users is a list of Users, we're setting a ClientUser self._users[user.id] = user # type: ignore if self.application_id is None: try: application = data['application'] except KeyError: pass else: self.application_id = utils._get_as_snowflake(application, 'id') self.application_flags = ApplicationFlags._from_value(application['flags']) for guild_data in data['guilds']: self._add_guild_from_data(guild_data) if self._messages: self._update_message_references() self.dispatch('connect') self.dispatch('shard_connect', data['__shard_id__']) if self._ready_task is None: self._ready_task = asyncio.create_task(self._delay_ready()) def parse_resumed(self, data) -> None: self.dispatch('resumed') self.dispatch('shard_resumed', data['__shard_id__'])
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/state.py
state.py
from __future__ import annotations import asyncio import logging import aiohttp from .state import AutoShardedConnectionState from .client import Client from .backoff import ExponentialBackoff from .gateway import * from .errors import ( ClientException, HTTPException, GatewayNotFound, ConnectionClosed, PrivilegedIntentsRequired, ) from .enums import Status from typing import TYPE_CHECKING, Any, Callable, Tuple, Type, Optional, List, Dict, TypeVar if TYPE_CHECKING: from .gateway import DiscordWebSocket from .activity import BaseActivity from .enums import Status EI = TypeVar('EI', bound='EventItem') __all__ = ( 'AutoShardedClient', 'ShardInfo', ) _log = logging.getLogger(__name__) class EventType: close = 0 reconnect = 1 resume = 2 identify = 3 terminate = 4 clean_close = 5 class EventItem: __slots__ = ('type', 'shard', 'error') def __init__(self, etype: int, shard: Optional['Shard'], error: Optional[Exception]) -> None: self.type: int = etype self.shard: Optional['Shard'] = shard self.error: Optional[Exception] = error def __lt__(self: EI, other: EI) -> bool: if not isinstance(other, EventItem): return NotImplemented return self.type < other.type def __eq__(self: EI, other: EI) -> bool: if not isinstance(other, EventItem): return NotImplemented return self.type == other.type def __hash__(self) -> int: return hash(self.type) class Shard: def __init__(self, ws: DiscordWebSocket, client: AutoShardedClient, queue_put: Callable[[EventItem], None]) -> None: self.ws: DiscordWebSocket = ws self._client: Client = client self._dispatch: Callable[..., None] = client.dispatch self._queue_put: Callable[[EventItem], None] = queue_put self.loop: asyncio.AbstractEventLoop = self._client.loop self._disconnect: bool = False self._reconnect = client._reconnect self._backoff: ExponentialBackoff = ExponentialBackoff() self._task: Optional[asyncio.Task] = None self._handled_exceptions: Tuple[Type[Exception], ...] = ( OSError, HTTPException, GatewayNotFound, ConnectionClosed, aiohttp.ClientError, asyncio.TimeoutError, ) @property def id(self) -> int: # DiscordWebSocket.shard_id is set in the from_client classmethod return self.ws.shard_id # type: ignore def launch(self) -> None: self._task = self.loop.create_task(self.worker()) def _cancel_task(self) -> None: if self._task is not None and not self._task.done(): self._task.cancel() async def close(self) -> None: self._cancel_task() await self.ws.close(code=1000) async def disconnect(self) -> None: await self.close() self._dispatch('shard_disconnect', self.id) async def _handle_disconnect(self, e: Exception) -> None: self._dispatch('disconnect') self._dispatch('shard_disconnect', self.id) if not self._reconnect: self._queue_put(EventItem(EventType.close, self, e)) return if self._client.is_closed(): return if isinstance(e, OSError) and e.errno in (54, 10054): # If we get Connection reset by peer then always try to RESUME the connection. exc = ReconnectWebSocket(self.id, resume=True) self._queue_put(EventItem(EventType.resume, self, exc)) return if isinstance(e, ConnectionClosed): if e.code == 4014: self._queue_put(EventItem(EventType.terminate, self, PrivilegedIntentsRequired(self.id))) return if e.code != 1000: self._queue_put(EventItem(EventType.close, self, e)) return retry = self._backoff.delay() _log.error('Attempting a reconnect for shard ID %s in %.2fs', self.id, retry, exc_info=e) await asyncio.sleep(retry) self._queue_put(EventItem(EventType.reconnect, self, e)) async def worker(self) -> None: while not self._client.is_closed(): try: await self.ws.poll_event() except ReconnectWebSocket as e: etype = EventType.resume if e.resume else EventType.identify self._queue_put(EventItem(etype, self, e)) break except self._handled_exceptions as e: await self._handle_disconnect(e) break except asyncio.CancelledError: break except Exception as e: self._queue_put(EventItem(EventType.terminate, self, e)) break async def reidentify(self, exc: ReconnectWebSocket) -> None: self._cancel_task() self._dispatch('disconnect') self._dispatch('shard_disconnect', self.id) _log.info('Got a request to %s the websocket at Shard ID %s.', exc.op, self.id) try: coro = DiscordWebSocket.from_client( self._client, resume=exc.resume, shard_id=self.id, session=self.ws.session_id, sequence=self.ws.sequence, ) self.ws = await asyncio.wait_for(coro, timeout=60.0) except self._handled_exceptions as e: await self._handle_disconnect(e) except asyncio.CancelledError: return except Exception as e: self._queue_put(EventItem(EventType.terminate, self, e)) else: self.launch() async def reconnect(self) -> None: self._cancel_task() try: coro = DiscordWebSocket.from_client(self._client, shard_id=self.id) self.ws = await asyncio.wait_for(coro, timeout=60.0) except self._handled_exceptions as e: await self._handle_disconnect(e) except asyncio.CancelledError: return except Exception as e: self._queue_put(EventItem(EventType.terminate, self, e)) else: self.launch() class ShardInfo: """A class that gives information and control over a specific shard. You can retrieve this object via :meth:`AutoShardedClient.get_shard` or :attr:`AutoShardedClient.shards`. .. versionadded:: 1.4 Attributes ------------ id: :class:`int` The shard ID for this shard. shard_count: Optional[:class:`int`] The shard count for this cluster. If this is ``None`` then the bot has not started yet. """ __slots__ = ('_parent', 'id', 'shard_count') def __init__(self, parent: Shard, shard_count: Optional[int]) -> None: self._parent: Shard = parent self.id: int = parent.id self.shard_count: Optional[int] = shard_count def is_closed(self) -> bool: """:class:`bool`: Whether the shard connection is currently closed.""" return not self._parent.ws.open async def disconnect(self) -> None: """|coro| Disconnects a shard. When this is called, the shard connection will no longer be open. If the shard is already disconnected this does nothing. """ if self.is_closed(): return await self._parent.disconnect() async def reconnect(self) -> None: """|coro| Disconnects and then connects the shard again. """ if not self.is_closed(): await self._parent.disconnect() await self._parent.reconnect() async def connect(self) -> None: """|coro| Connects a shard. If the shard is already connected this does nothing. """ if not self.is_closed(): return await self._parent.reconnect() @property def latency(self) -> float: """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds for this shard.""" return self._parent.ws.latency def is_ws_ratelimited(self) -> bool: """:class:`bool`: Whether the websocket is currently rate limited. This can be useful to know when deciding whether you should query members using HTTP or via the gateway. .. versionadded:: 1.6 """ return self._parent.ws.is_ratelimited() class AutoShardedClient(Client): """A client similar to :class:`Client` except it handles the complications of sharding for the user into a more manageable and transparent single process bot. When using this client, you will be able to use it as-if it was a regular :class:`Client` with a single shard when implementation wise internally it is split up into multiple shards. This allows you to not have to deal with IPC or other complicated infrastructure. It is recommended to use this client only if you have surpassed at least 1000 guilds. If no :attr:`.shard_count` is provided, then the library will use the Bot Gateway endpoint call to figure out how many shards to use. If a ``shard_ids`` parameter is given, then those shard IDs will be used to launch the internal shards. Note that :attr:`.shard_count` must be provided if this is used. By default, when omitted, the client will launch shards from 0 to ``shard_count - 1``. Attributes ------------ shard_ids: Optional[List[:class:`int`]] An optional list of shard_ids to launch the shards with. """ if TYPE_CHECKING: _connection: AutoShardedConnectionState def __init__(self, *args: Any, loop: Optional[asyncio.AbstractEventLoop] = None, **kwargs: Any) -> None: kwargs.pop('shard_id', None) self.shard_ids: Optional[List[int]] = kwargs.pop('shard_ids', None) super().__init__(*args, loop=loop, **kwargs) if self.shard_ids is not None: if self.shard_count is None: raise ClientException('When passing manual shard_ids, you must provide a shard_count.') elif not isinstance(self.shard_ids, (list, tuple)): raise ClientException('shard_ids parameter must be a list or a tuple.') # instead of a single websocket, we have multiple # the key is the shard_id self.__shards = {} self._connection._get_websocket = self._get_websocket self._connection._get_client = lambda: self self.__queue = asyncio.PriorityQueue() def _get_websocket(self, guild_id: Optional[int] = None, *, shard_id: Optional[int] = None) -> DiscordWebSocket: if shard_id is None: # guild_id won't be None if shard_id is None and shard_count won't be None here shard_id = (guild_id >> 22) % self.shard_count # type: ignore return self.__shards[shard_id].ws def _get_state(self, **options: Any) -> AutoShardedConnectionState: return AutoShardedConnectionState( dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, loop=self.loop, **options, ) @property def latency(self) -> float: """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This operates similarly to :meth:`Client.latency` except it uses the average latency of every shard's latency. To get a list of shard latency, check the :attr:`latencies` property. Returns ``nan`` if there are no shards ready. """ if not self.__shards: return float('nan') return sum(latency for _, latency in self.latencies) / len(self.__shards) @property def latencies(self) -> List[Tuple[int, float]]: """List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This returns a list of tuples with elements ``(shard_id, latency)``. """ return [(shard_id, shard.ws.latency) for shard_id, shard in self.__shards.items()] def get_shard(self, shard_id: int) -> Optional[ShardInfo]: """Optional[:class:`ShardInfo`]: Gets the shard information at a given shard ID or ``None`` if not found.""" try: parent = self.__shards[shard_id] except KeyError: return None else: return ShardInfo(parent, self.shard_count) @property def shards(self) -> Dict[int, ShardInfo]: """Mapping[int, :class:`ShardInfo`]: Returns a mapping of shard IDs to their respective info object.""" return {shard_id: ShardInfo(parent, self.shard_count) for shard_id, parent in self.__shards.items()} async def launch_shard(self, gateway: str, shard_id: int, *, initial: bool = False) -> None: try: coro = DiscordWebSocket.from_client(self, initial=initial, gateway=gateway, shard_id=shard_id) ws = await asyncio.wait_for(coro, timeout=180.0) except Exception: _log.exception('Failed to connect for shard_id: %s. Retrying...', shard_id) await asyncio.sleep(5.0) return await self.launch_shard(gateway, shard_id) # keep reading the shard while others connect self.__shards[shard_id] = ret = Shard(ws, self, self.__queue.put_nowait) ret.launch() async def launch_shards(self) -> None: if self.shard_count is None: self.shard_count, gateway = await self.http.get_bot_gateway() else: gateway = await self.http.get_gateway() self._connection.shard_count = self.shard_count shard_ids = self.shard_ids or range(self.shard_count) self._connection.shard_ids = shard_ids for shard_id in shard_ids: initial = shard_id == shard_ids[0] await self.launch_shard(gateway, shard_id, initial=initial) self._connection.shards_launched.set() async def connect(self, *, reconnect: bool = True) -> None: self._reconnect = reconnect await self.launch_shards() while not self.is_closed(): item = await self.__queue.get() if item.type == EventType.close: await self.close() if isinstance(item.error, ConnectionClosed): if item.error.code != 1000: raise item.error if item.error.code == 4014: raise PrivilegedIntentsRequired(item.shard.id) from None return elif item.type in (EventType.identify, EventType.resume): await item.shard.reidentify(item.error) elif item.type == EventType.reconnect: await item.shard.reconnect() elif item.type == EventType.terminate: await self.close() raise item.error elif item.type == EventType.clean_close: return async def close(self) -> None: """|coro| Closes the connection to Discord. """ if self.is_closed(): return self._closed = True for vc in self.voice_clients: try: await vc.disconnect(force=True) except Exception: pass to_close = [asyncio.ensure_future(shard.close(), loop=self.loop) for shard in self.__shards.values()] if to_close: await asyncio.wait(to_close) await self.http.close() self.__queue.put_nowait(EventItem(EventType.clean_close, None, None)) async def change_presence( self, *, activity: Optional[BaseActivity] = None, status: Optional[Status] = None, shard_id: int = None, ) -> None: """|coro| Changes the client's presence. Example: :: game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) .. versionchanged:: 2.0 Removed the ``afk`` keyword-only parameter. Parameters ---------- activity: Optional[:class:`BaseActivity`] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`Status`] Indicates what status to change to. If ``None``, then :attr:`Status.online` is used. shard_id: Optional[:class:`int`] The shard_id to change the presence to. If not specified or ``None``, then it will change the presence of every shard the bot can see. Raises ------ InvalidArgument If the ``activity`` parameter is not of proper type. """ if status is None: status_value = 'online' status_enum = Status.online elif status is Status.offline: status_value = 'invisible' status_enum = Status.offline else: status_enum = status status_value = str(status) if shard_id is None: for shard in self.__shards.values(): await shard.ws.change_presence(activity=activity, status=status_value) guilds = self._connection.guilds else: shard = self.__shards[shard_id] await shard.ws.change_presence(activity=activity, status=status_value) guilds = [g for g in self._connection.guilds if g.shard_id == shard_id] activities = () if activity is None else (activity,) for guild in guilds: me = guild.me if me is None: continue # Member.activities is typehinted as Tuple[ActivityType, ...], we may be setting it as Tuple[BaseActivity, ...] me.activities = activities # type: ignore me.status = status_enum def is_ws_ratelimited(self) -> bool: """:class:`bool`: Whether the websocket is currently rate limited. This can be useful to know when deciding whether you should query members using HTTP or via the gateway. This implementation checks if any of the shards are rate limited. For more granular control, consider :meth:`ShardInfo.is_ws_ratelimited`. .. versionadded:: 1.6 """ return any(shard.ws.is_ratelimited() for shard in self.__shards.values())
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/shard.py
shard.py
from __future__ import annotations from typing import Any, Callable, ClassVar, Dict, Generic, Iterator, List, Optional, Tuple, Type, TypeVar, overload from .enums import UserFlags __all__ = ( 'SystemChannelFlags', 'MessageFlags', 'PublicUserFlags', 'Intents', 'MemberCacheFlags', 'ApplicationFlags', ) FV = TypeVar('FV', bound='flag_value') BF = TypeVar('BF', bound='BaseFlags') class flag_value: def __init__(self, func: Callable[[Any], int]): self.flag = func(None) self.__doc__ = func.__doc__ @overload def __get__(self: FV, instance: None, owner: Type[BF]) -> FV: ... @overload 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: BF, value: bool) -> None: instance._set_flag(self.flag, value) def __repr__(self): return f'<flag_value flag={self.flag!r}>' class alias_flag_value(flag_value): pass def fill_with_flags(*, inverted: bool = False): def decorator(cls: Type[BF]): # fmt: off cls.VALID_FLAGS = { name: value.flag for name, value in cls.__dict__.items() if isinstance(value, flag_value) } # fmt: on 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 # n.b. flags must inherit from this and use the decorator above class BaseFlags: VALID_FLAGS: ClassVar[Dict[str, int]] DEFAULT_VALUE: ClassVar[int] value: int __slots__ = ('value',) def __init__(self, **kwargs: bool): self.value = self.DEFAULT_VALUE for key, value in kwargs.items(): if key not in self.VALID_FLAGS: raise TypeError(f'{key!r} is not a valid flag name.') setattr(self, key, value) @classmethod def _from_value(cls, value): self = cls.__new__(cls) self.value = value return self def __eq__(self, other: Any) -> bool: return isinstance(other, self.__class__) and self.value == other.value def __ne__(self, other: Any) -> bool: return not self.__eq__(other) def __hash__(self) -> int: return hash(self.value) def __repr__(self) -> str: return f'<{self.__class__.__name__} value={self.value}>' def __iter__(self) -> Iterator[Tuple[str, bool]]: for name, value in self.__class__.__dict__.items(): if isinstance(value, alias_flag_value): continue if isinstance(value, flag_value): yield (name, self._has_flag(value.flag)) def _has_flag(self, o: int) -> bool: return (self.value & o) == o def _set_flag(self, o: int, toggle: bool) -> None: if toggle is True: self.value |= o elif toggle is False: self.value &= ~o else: raise TypeError(f'Value to set for {self.__class__.__name__} must be a bool.') @fill_with_flags(inverted=True) class SystemChannelFlags(BaseFlags): r"""Wraps up a Discord system channel flag value. Similar to :class:`Permissions`\, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit the system flags easily. To construct an object you can pass keyword arguments denoting the flags to enable or disable. .. container:: operations .. describe:: x == y Checks if two flags are equal. .. describe:: x != y Checks if two flags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Attributes ----------- value: :class:`int` The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value. """ __slots__ = () # For some reason the flags for system channels are "inverted" # ergo, if they're set then it means "suppress" (off in the GUI toggle) # Since this is counter-intuitive from an API perspective and annoying # these will be inverted automatically def _has_flag(self, o: int) -> bool: return (self.value & o) != o def _set_flag(self, o: int, toggle: bool) -> None: if toggle is True: self.value &= ~o elif toggle is False: self.value |= o else: raise TypeError('Value to set for SystemChannelFlags must be a bool.') @flag_value def join_notifications(self): """:class:`bool`: Returns ``True`` if the system channel is used for member join notifications.""" return 1 @flag_value def premium_subscriptions(self): """:class:`bool`: Returns ``True`` if the system channel is used for "Nitro boosting" notifications.""" return 2 @flag_value def guild_reminder_notifications(self): """:class:`bool`: Returns ``True`` if the system channel is used for server setup helpful tips notifications. .. versionadded:: 2.0 """ return 4 @fill_with_flags() class MessageFlags(BaseFlags): r"""Wraps up a Discord Message flag value. See :class:`SystemChannelFlags`. .. container:: operations .. describe:: x == y Checks if two flags are equal. .. describe:: x != y Checks if two flags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. .. versionadded:: 1.3 Attributes ----------- value: :class:`int` The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value. """ __slots__ = () @flag_value def crossposted(self): """:class:`bool`: Returns ``True`` if the message is the original crossposted message.""" return 1 @flag_value def is_crossposted(self): """:class:`bool`: Returns ``True`` if the message was crossposted from another channel.""" return 2 @flag_value def suppress_embeds(self): """:class:`bool`: Returns ``True`` if the message's embeds have been suppressed.""" return 4 @flag_value def source_message_deleted(self): """:class:`bool`: Returns ``True`` if the source message for this crosspost has been deleted.""" return 8 @flag_value def urgent(self): """:class:`bool`: Returns ``True`` if the source message is an urgent message. An urgent message is one sent by Discord Trust and Safety. """ return 16 @flag_value def has_thread(self): """:class:`bool`: Returns ``True`` if the source message is associated with a thread. .. versionadded:: 2.0 """ return 32 @flag_value def ephemeral(self): """:class:`bool`: Returns ``True`` if the source message is ephemeral. .. versionadded:: 2.0 """ return 64 @fill_with_flags() class PublicUserFlags(BaseFlags): r"""Wraps up the Discord User Public flags. .. container:: operations .. describe:: x == y Checks if two PublicUserFlags are equal. .. describe:: x != y Checks if two PublicUserFlags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown. .. versionadded:: 1.4 Attributes ----------- value: :class:`int` The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value. """ __slots__ = () @flag_value def staff(self): """:class:`bool`: Returns ``True`` if the user is a Discord Employee.""" return UserFlags.staff.value @flag_value def partner(self): """:class:`bool`: Returns ``True`` if the user is a Discord Partner.""" return UserFlags.partner.value @flag_value def hypesquad(self): """:class:`bool`: Returns ``True`` if the user is a HypeSquad Events member.""" return UserFlags.hypesquad.value @flag_value def bug_hunter(self): """:class:`bool`: Returns ``True`` if the user is a Bug Hunter""" return UserFlags.bug_hunter.value @flag_value def hypesquad_bravery(self): """:class:`bool`: Returns ``True`` if the user is a HypeSquad Bravery member.""" return UserFlags.hypesquad_bravery.value @flag_value def hypesquad_brilliance(self): """:class:`bool`: Returns ``True`` if the user is a HypeSquad Brilliance member.""" return UserFlags.hypesquad_brilliance.value @flag_value def hypesquad_balance(self): """:class:`bool`: Returns ``True`` if the user is a HypeSquad Balance member.""" return UserFlags.hypesquad_balance.value @flag_value def early_supporter(self): """:class:`bool`: Returns ``True`` if the user is an Early Supporter.""" return UserFlags.early_supporter.value @flag_value def team_user(self): """:class:`bool`: Returns ``True`` if the user is a Team User.""" return UserFlags.team_user.value @flag_value def system(self): """:class:`bool`: Returns ``True`` if the user is a system user (i.e. represents Discord officially).""" return UserFlags.system.value @flag_value def bug_hunter_level_2(self): """:class:`bool`: Returns ``True`` if the user is a Bug Hunter Level 2""" return UserFlags.bug_hunter_level_2.value @flag_value def verified_bot(self): """:class:`bool`: Returns ``True`` if the user is a Verified Bot.""" return UserFlags.verified_bot.value @flag_value def verified_bot_developer(self): """:class:`bool`: Returns ``True`` if the user is an Early Verified Bot Developer.""" return UserFlags.verified_bot_developer.value @alias_flag_value def early_verified_bot_developer(self): """:class:`bool`: An alias for :attr:`verified_bot_developer`. .. versionadded:: 1.5 """ return UserFlags.verified_bot_developer.value @flag_value def discord_certified_moderator(self): """:class:`bool`: Returns ``True`` if the user is a Discord Certified Moderator. .. versionadded:: 2.0 """ return UserFlags.discord_certified_moderator.value def all(self) -> List[UserFlags]: """List[:class:`UserFlags`]: Returns all public flags the user has.""" return [public_flag for public_flag in UserFlags if self._has_flag(public_flag.value)] @fill_with_flags() class Intents(BaseFlags): r"""Wraps up a Discord gateway intent flag. Similar to :class:`Permissions`\, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. To construct an object you can pass keyword arguments denoting the flags to enable or disable. This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the ``intents`` keyword argument of :class:`Client`. .. versionadded:: 1.5 .. container:: operations .. describe:: x == y Checks if two flags are equal. .. describe:: x != y Checks if two flags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Attributes ----------- value: :class:`int` The raw value. You should query flags via the properties rather than using this raw value. """ __slots__ = () def __init__(self, **kwargs: bool): self.value = self.DEFAULT_VALUE for key, value in kwargs.items(): if key not in self.VALID_FLAGS: raise TypeError(f'{key!r} is not a valid flag name.') setattr(self, key, value) @classmethod def all(cls: Type[Intents]) -> Intents: """A factory method that creates a :class:`Intents` with everything enabled.""" bits = max(cls.VALID_FLAGS.values()).bit_length() value = (1 << bits) - 1 self = cls.__new__(cls) self.value = value return self @classmethod def none(cls: Type[Intents]) -> Intents: """A factory method that creates a :class:`Intents` with everything disabled.""" self = cls.__new__(cls) self.value = self.DEFAULT_VALUE return self @classmethod def default(cls: Type[Intents]) -> Intents: """A factory method that creates a :class:`Intents` with everything enabled except :attr:`presences` and :attr:`members`. """ self = cls.all() self.presences = False self.members = False return self @flag_value def guilds(self): """:class:`bool`: Whether guild related events are enabled. This corresponds to the following events: - :func:`on_guild_join` - :func:`on_guild_remove` - :func:`on_guild_available` - :func:`on_guild_unavailable` - :func:`on_guild_channel_update` - :func:`on_guild_channel_create` - :func:`on_guild_channel_delete` - :func:`on_guild_channel_pins_update` This also corresponds to the following attributes and classes in terms of cache: - :attr:`Client.guilds` - :class:`Guild` and all its attributes. - :meth:`Client.get_channel` - :meth:`Client.get_all_channels` It is highly advisable to leave this intent enabled for your bot to function. """ return 1 << 0 @flag_value def members(self): """:class:`bool`: Whether guild member related events are enabled. This corresponds to the following events: - :func:`on_member_join` - :func:`on_member_remove` - :func:`on_member_update` - :func:`on_user_update` This also corresponds to the following attributes and classes in terms of cache: - :meth:`Client.get_all_members` - :meth:`Client.get_user` - :meth:`Guild.chunk` - :meth:`Guild.fetch_members` - :meth:`Guild.get_member` - :attr:`Guild.members` - :attr:`Member.roles` - :attr:`Member.nick` - :attr:`Member.premium_since` - :attr:`User.name` - :attr:`User.avatar` - :attr:`User.discriminator` For more information go to the :ref:`member intent documentation <need_members_intent>`. .. note:: Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification. """ return 1 << 1 @flag_value def bans(self): """:class:`bool`: Whether guild ban related events are enabled. This corresponds to the following events: - :func:`on_member_ban` - :func:`on_member_unban` This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 2 @flag_value def emojis(self): """:class:`bool`: Alias of :attr:`.emojis_and_stickers`. .. versionchanged:: 2.0 Changed to an alias. """ return 1 << 3 @alias_flag_value def emojis_and_stickers(self): """:class:`bool`: Whether guild emoji and sticker related events are enabled. .. versionadded:: 2.0 This corresponds to the following events: - :func:`on_guild_emojis_update` - :func:`on_guild_stickers_update` This also corresponds to the following attributes and classes in terms of cache: - :class:`Emoji` - :class:`GuildSticker` - :meth:`Client.get_emoji` - :meth:`Client.get_sticker` - :meth:`Client.emojis` - :meth:`Client.stickers` - :attr:`Guild.emojis` - :attr:`Guild.stickers` """ return 1 << 3 @flag_value def integrations(self): """:class:`bool`: Whether guild integration related events are enabled. This corresponds to the following events: - :func:`on_guild_integrations_update` - :func:`on_integration_create` - :func:`on_integration_update` - :func:`on_raw_integration_delete` This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 4 @flag_value def webhooks(self): """:class:`bool`: Whether guild webhook related events are enabled. This corresponds to the following events: - :func:`on_webhooks_update` This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 5 @flag_value def invites(self): """:class:`bool`: Whether guild invite related events are enabled. This corresponds to the following events: - :func:`on_invite_create` - :func:`on_invite_delete` This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 6 @flag_value def voice_states(self): """:class:`bool`: Whether guild voice state related events are enabled. This corresponds to the following events: - :func:`on_voice_state_update` This also corresponds to the following attributes and classes in terms of cache: - :attr:`VoiceChannel.members` - :attr:`VoiceChannel.voice_states` - :attr:`Member.voice` .. note:: This intent is required to connect to voice. """ return 1 << 7 @flag_value def presences(self): """:class:`bool`: Whether guild presence related events are enabled. This corresponds to the following events: - :func:`on_presence_update` This also corresponds to the following attributes and classes in terms of cache: - :attr:`Member.activities` - :attr:`Member.status` - :attr:`Member.raw_status` For more information go to the :ref:`presence intent documentation <need_presence_intent>`. .. note:: Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification. """ return 1 << 8 @alias_flag_value def messages(self): """:class:`bool`: Whether guild and direct message related events are enabled. This is a shortcut to set or get both :attr:`guild_messages` and :attr:`dm_messages`. This corresponds to the following events: - :func:`on_message` (both guilds and DMs) - :func:`on_message_edit` (both guilds and DMs) - :func:`on_message_delete` (both guilds and DMs) - :func:`on_raw_message_delete` (both guilds and DMs) - :func:`on_raw_message_edit` (both guilds and DMs) This also corresponds to the following attributes and classes in terms of cache: - :class:`Message` - :attr:`Client.cached_messages` Note that due to an implicit relationship this also corresponds to the following events: - :func:`on_reaction_add` (both guilds and DMs) - :func:`on_reaction_remove` (both guilds and DMs) - :func:`on_reaction_clear` (both guilds and DMs) """ return (1 << 9) | (1 << 12) @flag_value def guild_messages(self): """:class:`bool`: Whether guild message related events are enabled. See also :attr:`dm_messages` for DMs or :attr:`messages` for both. This corresponds to the following events: - :func:`on_message` (only for guilds) - :func:`on_message_edit` (only for guilds) - :func:`on_message_delete` (only for guilds) - :func:`on_raw_message_delete` (only for guilds) - :func:`on_raw_message_edit` (only for guilds) This also corresponds to the following attributes and classes in terms of cache: - :class:`Message` - :attr:`Client.cached_messages` (only for guilds) Note that due to an implicit relationship this also corresponds to the following events: - :func:`on_reaction_add` (only for guilds) - :func:`on_reaction_remove` (only for guilds) - :func:`on_reaction_clear` (only for guilds) """ return 1 << 9 @flag_value def dm_messages(self): """:class:`bool`: Whether direct message related events are enabled. See also :attr:`guild_messages` for guilds or :attr:`messages` for both. This corresponds to the following events: - :func:`on_message` (only for DMs) - :func:`on_message_edit` (only for DMs) - :func:`on_message_delete` (only for DMs) - :func:`on_raw_message_delete` (only for DMs) - :func:`on_raw_message_edit` (only for DMs) This also corresponds to the following attributes and classes in terms of cache: - :class:`Message` - :attr:`Client.cached_messages` (only for DMs) Note that due to an implicit relationship this also corresponds to the following events: - :func:`on_reaction_add` (only for DMs) - :func:`on_reaction_remove` (only for DMs) - :func:`on_reaction_clear` (only for DMs) """ return 1 << 12 @alias_flag_value def reactions(self): """:class:`bool`: Whether guild and direct message reaction related events are enabled. This is a shortcut to set or get both :attr:`guild_reactions` and :attr:`dm_reactions`. This corresponds to the following events: - :func:`on_reaction_add` (both guilds and DMs) - :func:`on_reaction_remove` (both guilds and DMs) - :func:`on_reaction_clear` (both guilds and DMs) - :func:`on_raw_reaction_add` (both guilds and DMs) - :func:`on_raw_reaction_remove` (both guilds and DMs) - :func:`on_raw_reaction_clear` (both guilds and DMs) This also corresponds to the following attributes and classes in terms of cache: - :attr:`Message.reactions` (both guild and DM messages) """ return (1 << 10) | (1 << 13) @flag_value def guild_reactions(self): """:class:`bool`: Whether guild message reaction related events are enabled. See also :attr:`dm_reactions` for DMs or :attr:`reactions` for both. This corresponds to the following events: - :func:`on_reaction_add` (only for guilds) - :func:`on_reaction_remove` (only for guilds) - :func:`on_reaction_clear` (only for guilds) - :func:`on_raw_reaction_add` (only for guilds) - :func:`on_raw_reaction_remove` (only for guilds) - :func:`on_raw_reaction_clear` (only for guilds) This also corresponds to the following attributes and classes in terms of cache: - :attr:`Message.reactions` (only for guild messages) """ return 1 << 10 @flag_value def dm_reactions(self): """:class:`bool`: Whether direct message reaction related events are enabled. See also :attr:`guild_reactions` for guilds or :attr:`reactions` for both. This corresponds to the following events: - :func:`on_reaction_add` (only for DMs) - :func:`on_reaction_remove` (only for DMs) - :func:`on_reaction_clear` (only for DMs) - :func:`on_raw_reaction_add` (only for DMs) - :func:`on_raw_reaction_remove` (only for DMs) - :func:`on_raw_reaction_clear` (only for DMs) This also corresponds to the following attributes and classes in terms of cache: - :attr:`Message.reactions` (only for DM messages) """ return 1 << 13 @alias_flag_value def typing(self): """:class:`bool`: Whether guild and direct message typing related events are enabled. This is a shortcut to set or get both :attr:`guild_typing` and :attr:`dm_typing`. This corresponds to the following events: - :func:`on_typing` (both guilds and DMs) This does not correspond to any attributes or classes in the library in terms of cache. """ return (1 << 11) | (1 << 14) @flag_value def guild_typing(self): """:class:`bool`: Whether guild and direct message typing related events are enabled. See also :attr:`dm_typing` for DMs or :attr:`typing` for both. This corresponds to the following events: - :func:`on_typing` (only for guilds) This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 11 @flag_value def dm_typing(self): """:class:`bool`: Whether guild and direct message typing related events are enabled. See also :attr:`guild_typing` for guilds or :attr:`typing` for both. This corresponds to the following events: - :func:`on_typing` (only for DMs) This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 14 @fill_with_flags() class MemberCacheFlags(BaseFlags): """Controls the library's cache policy when it comes to members. This allows for finer grained control over what members are cached. Note that the bot's own member is always cached. This class is passed to the ``member_cache_flags`` parameter in :class:`Client`. Due to a quirk in how Discord works, in order to ensure proper cleanup of cache resources it is recommended to have :attr:`Intents.members` enabled. Otherwise the library cannot know when a member leaves a guild and is thus unable to cleanup after itself. To construct an object you can pass keyword arguments denoting the flags to enable or disable. The default value is all flags enabled. .. versionadded:: 1.5 .. container:: operations .. describe:: x == y Checks if two flags are equal. .. describe:: x != y Checks if two flags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Attributes ----------- value: :class:`int` The raw value. You should query flags via the properties rather than using this raw value. """ __slots__ = () def __init__(self, **kwargs: bool): bits = max(self.VALID_FLAGS.values()).bit_length() self.value = (1 << bits) - 1 for key, value in kwargs.items(): if key not in self.VALID_FLAGS: raise TypeError(f'{key!r} is not a valid flag name.') setattr(self, key, value) @classmethod def all(cls: Type[MemberCacheFlags]) -> MemberCacheFlags: """A factory method that creates a :class:`MemberCacheFlags` with everything enabled.""" bits = max(cls.VALID_FLAGS.values()).bit_length() value = (1 << bits) - 1 self = cls.__new__(cls) self.value = value return self @classmethod def none(cls: Type[MemberCacheFlags]) -> MemberCacheFlags: """A factory method that creates a :class:`MemberCacheFlags` with everything disabled.""" self = cls.__new__(cls) self.value = self.DEFAULT_VALUE return self @property def _empty(self): return self.value == self.DEFAULT_VALUE @flag_value def voice(self): """:class:`bool`: Whether to cache members that are in voice. This requires :attr:`Intents.voice_states`. Members that leave voice are no longer cached. """ return 1 @flag_value def joined(self): """:class:`bool`: Whether to cache members that joined the guild or are chunked as part of the initial log in flow. This requires :attr:`Intents.members`. Members that leave the guild are no longer cached. """ return 2 @classmethod def from_intents(cls: Type[MemberCacheFlags], intents: Intents) -> MemberCacheFlags: """A factory method that creates a :class:`MemberCacheFlags` based on the currently selected :class:`Intents`. Parameters ------------ intents: :class:`Intents` The intents to select from. Returns --------- :class:`MemberCacheFlags` The resulting member cache flags. """ self = cls.none() if intents.members: self.joined = True if intents.voice_states: self.voice = True return self def _verify_intents(self, intents: Intents): if self.voice and not intents.voice_states: raise ValueError('MemberCacheFlags.voice requires Intents.voice_states') if self.joined and not intents.members: raise ValueError('MemberCacheFlags.joined requires Intents.members') @property def _voice_only(self): return self.value == 1 @fill_with_flags() class ApplicationFlags(BaseFlags): r"""Wraps up the Discord Application flags. .. container:: operations .. describe:: x == y Checks if two ApplicationFlags are equal. .. describe:: x != y Checks if two ApplicationFlags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown. .. versionadded:: 2.0 Attributes ----------- value: :class:`int` The raw value. You should query flags via the properties rather than using this raw value. """ @flag_value def gateway_presence(self): """:class:`bool`: Returns ``True`` if the application is verified and is allowed to receive presence information over the gateway. """ return 1 << 12 @flag_value def gateway_presence_limited(self): """:class:`bool`: Returns ``True`` if the application is allowed to receive limited presence information over the gateway. """ return 1 << 13 @flag_value def gateway_guild_members(self): """:class:`bool`: Returns ``True`` if the application is verified and is allowed to receive guild members information over the gateway. """ return 1 << 14 @flag_value def gateway_guild_members_limited(self): """:class:`bool`: Returns ``True`` if the application is allowed to receive limited guild members information over the gateway. """ return 1 << 15 @flag_value def verification_pending_guild_limit(self): """:class:`bool`: Returns ``True`` if the application is currently pending verification and has hit the guild limit. """ return 1 << 16 @flag_value def embedded(self): """:class:`bool`: Returns ``True`` if the application is embedded within the Discord client.""" return 1 << 17
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/flags.py
flags.py
from __future__ import annotations from typing import Any, Dict, Optional, TYPE_CHECKING, Type, TypeVar, Union import re from .asset import Asset, AssetMixin from .errors import InvalidArgument from . import utils __all__ = ( 'PartialEmoji', ) if TYPE_CHECKING: from .state import ConnectionState from datetime import datetime from .types.message import PartialEmoji as PartialEmojiPayload class _EmojiTag: __slots__ = () id: int def _to_partial(self) -> PartialEmoji: raise NotImplementedError PE = TypeVar('PE', bound='PartialEmoji') class PartialEmoji(_EmojiTag, AssetMixin): """Represents a "partial" emoji. This model will be given in two scenarios: - "Raw" data events such as :func:`on_raw_reaction_add` - Custom emoji that the bot cannot see from e.g. :attr:`Message.reactions` .. container:: operations .. describe:: x == y Checks if two emoji are the same. .. describe:: x != y Checks if two emoji are not the same. .. describe:: hash(x) Return the emoji's hash. .. describe:: str(x) Returns the emoji rendered for discord. Attributes ----------- name: Optional[:class:`str`] The custom emoji name, if applicable, or the unicode codepoint of the non-custom emoji. This can be ``None`` if the emoji got deleted (e.g. removing a reaction with a deleted emoji). animated: :class:`bool` Whether the emoji is animated or not. id: Optional[:class:`int`] The ID of the custom emoji, if applicable. """ __slots__ = ('animated', 'name', 'id', '_state') _CUSTOM_EMOJI_RE = re.compile(r'<?(?P<animated>a)?:?(?P<name>[A-Za-z0-9\_]+):(?P<id>[0-9]{13,20})>?') if TYPE_CHECKING: id: Optional[int] def __init__(self, *, name: str, animated: bool = False, id: Optional[int] = None): self.animated = animated self.name = name self.id = id self._state: Optional[ConnectionState] = None @classmethod def from_dict(cls: Type[PE], data: Union[PartialEmojiPayload, Dict[str, Any]]) -> PE: return cls( animated=data.get('animated', False), id=utils._get_as_snowflake(data, 'id'), name=data.get('name') or '', ) @classmethod def from_str(cls: Type[PE], value: str) -> PE: """Converts a Discord string representation of an emoji to a :class:`PartialEmoji`. The formats accepted are: - ``a:name:id`` - ``<a:name:id>`` - ``name:id`` - ``<:name:id>`` If the format does not match then it is assumed to be a unicode emoji. .. versionadded:: 2.0 Parameters ------------ value: :class:`str` The string representation of an emoji. Returns -------- :class:`PartialEmoji` The partial emoji from this string. """ match = cls._CUSTOM_EMOJI_RE.match(value) if match is not None: groups = match.groupdict() animated = bool(groups['animated']) emoji_id = int(groups['id']) name = groups['name'] return cls(name=name, animated=animated, id=emoji_id) return cls(name=value, id=None, animated=False) def to_dict(self) -> Dict[str, Any]: o: Dict[str, Any] = {'name': self.name} if self.id: o['id'] = self.id if self.animated: o['animated'] = self.animated return o def _to_partial(self) -> PartialEmoji: return self @classmethod def with_state( cls: Type[PE], state: ConnectionState, *, name: str, animated: bool = False, id: Optional[int] = None ) -> PE: self = cls(name=name, animated=animated, id=id) self._state = state return self def __str__(self) -> str: if self.id is None: return self.name if self.animated: return f'<a:{self.name}:{self.id}>' return f'<:{self.name}:{self.id}>' def __repr__(self): return f'<{self.__class__.__name__} animated={self.animated} name={self.name!r} id={self.id}>' def __eq__(self, other: Any) -> bool: if self.is_unicode_emoji(): return isinstance(other, PartialEmoji) and self.name == other.name if isinstance(other, _EmojiTag): return self.id == other.id return False def __ne__(self, other: Any) -> bool: return not self.__eq__(other) def __hash__(self) -> int: return hash((self.id, self.name)) def is_custom_emoji(self) -> bool: """:class:`bool`: Checks if this is a custom non-Unicode emoji.""" return self.id is not None def is_unicode_emoji(self) -> bool: """:class:`bool`: Checks if this is a Unicode emoji.""" return self.id is None def _as_reaction(self) -> str: if self.id is None: return self.name return f'{self.name}:{self.id}' @property def created_at(self) -> Optional[datetime]: """Optional[:class:`datetime.datetime`]: Returns the emoji's creation time in UTC, or None if Unicode emoji. .. versionadded:: 1.6 """ if self.id is None: return None return utils.snowflake_time(self.id) @property def url(self) -> str: """:class:`str`: Returns the URL of the emoji, if it is custom. If this isn't a custom emoji then an empty string is returned """ if self.is_unicode_emoji(): return '' fmt = 'gif' if self.animated else 'png' return f'{Asset.BASE}/emojis/{self.id}.{fmt}' async def read(self) -> bytes: if self.is_unicode_emoji(): raise InvalidArgument('PartialEmoji is not a custom emoji') return await super().read()
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/partial_emoji.py
partial_emoji.py
from __future__ import annotations from . import utils from .user import BaseUser from .asset import Asset from .enums import TeamMembershipState, try_enum from typing import TYPE_CHECKING, Optional, List if TYPE_CHECKING: from .state import ConnectionState from .types.team import ( Team as TeamPayload, TeamMember as TeamMemberPayload, ) __all__ = ( 'Team', 'TeamMember', ) class Team: """Represents an application team for a bot provided by Discord. Attributes ------------- id: :class:`int` The team ID. name: :class:`str` The team name owner_id: :class:`int` The team's owner ID. members: List[:class:`TeamMember`] A list of the members in the team .. versionadded:: 1.3 """ __slots__ = ('_state', 'id', 'name', '_icon', 'owner_id', 'members') def __init__(self, state: ConnectionState, data: TeamPayload): self._state: ConnectionState = state self.id: int = int(data['id']) self.name: str = data['name'] self._icon: Optional[str] = data['icon'] self.owner_id: Optional[int] = utils._get_as_snowflake(data, 'owner_user_id') self.members: List[TeamMember] = [TeamMember(self, self._state, member) for member in data['members']] def __repr__(self) -> str: return f'<{self.__class__.__name__} id={self.id} name={self.name}>' @property def icon(self) -> Optional[Asset]: """Optional[:class:`.Asset`]: Retrieves the team's icon asset, if any.""" if self._icon is None: return None return Asset._from_icon(self._state, self.id, self._icon, path='team') @property def owner(self) -> Optional[TeamMember]: """Optional[:class:`TeamMember`]: The team's owner.""" return utils.get(self.members, id=self.owner_id) class TeamMember(BaseUser): """Represents a team member in a team. .. container:: operations .. describe:: x == y Checks if two team members are equal. .. describe:: x != y Checks if two team members are not equal. .. describe:: hash(x) Return the team member's hash. .. describe:: str(x) Returns the team member's name with discriminator. .. versionadded:: 1.3 Attributes ------------- name: :class:`str` The team member's username. id: :class:`int` The team member's unique ID. discriminator: :class:`str` The team member's discriminator. This is given when the username has conflicts. avatar: Optional[:class:`str`] The avatar hash the team member has. Could be None. bot: :class:`bool` Specifies if the user is a bot account. team: :class:`Team` The team that the member is from. membership_state: :class:`TeamMembershipState` The membership state of the member (e.g. invited or accepted) """ __slots__ = ('team', 'membership_state', 'permissions') def __init__(self, team: Team, state: ConnectionState, data: TeamMemberPayload): self.team: Team = team self.membership_state: TeamMembershipState = try_enum(TeamMembershipState, data['membership_state']) self.permissions: List[str] = data['permissions'] super().__init__(state=state, data=data['user']) def __repr__(self) -> str: return ( f'<{self.__class__.__name__} id={self.id} name={self.name!r} ' f'discriminator={self.discriminator!r} membership_state={self.membership_state!r}>' )
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/team.py
team.py
from __future__ import annotations import datetime import inspect import itertools import sys from operator import attrgetter from typing import Any, Dict, List, Literal, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Union, overload import discord.abc from . import utils from .asset import Asset from .utils import MISSING from .user import BaseUser, User, _UserTag from .activity import create_activity, ActivityTypes from .permissions import Permissions from .enums import Status, try_enum from .colour import Colour from .object import Object __all__ = ( 'VoiceState', 'Member', ) if TYPE_CHECKING: from .asset import Asset from .channel import DMChannel, VoiceChannel, StageChannel from .flags import PublicUserFlags from .guild import Guild from .types.activity import PartialPresenceUpdate from .types.member import ( MemberWithUser as MemberWithUserPayload, Member as MemberPayload, UserWithMember as UserWithMemberPayload, ) from .types.user import User as UserPayload from .abc import Snowflake from .state import ConnectionState from .message import Message from .role import Role from .types.voice import VoiceState as VoiceStatePayload VocalGuildChannel = Union[VoiceChannel, StageChannel] class VoiceState: """Represents a Discord user's voice state. Attributes ------------ deaf: :class:`bool` Indicates if the user is currently deafened by the guild. mute: :class:`bool` Indicates if the user is currently muted by the guild. self_mute: :class:`bool` Indicates if the user is currently muted by their own accord. self_deaf: :class:`bool` Indicates if the user is currently deafened by their own accord. self_stream: :class:`bool` Indicates if the user is currently streaming via 'Go Live' feature. .. versionadded:: 1.3 self_video: :class:`bool` Indicates if the user is currently broadcasting video. suppress: :class:`bool` Indicates if the user is suppressed from speaking. Only applies to stage channels. .. versionadded:: 1.7 requested_to_speak_at: Optional[:class:`datetime.datetime`] An aware datetime object that specifies the date and time in UTC that the member requested to speak. It will be ``None`` if they are not requesting to speak anymore or have been accepted to speak. Only applicable to stage channels. .. versionadded:: 1.7 afk: :class:`bool` Indicates if the user is currently in the AFK channel in the guild. channel: Optional[Union[:class:`VoiceChannel`, :class:`StageChannel`]] The voice channel that the user is currently connected to. ``None`` if the user is not currently in a voice channel. """ __slots__ = ( 'session_id', 'deaf', 'mute', 'self_mute', 'self_stream', 'self_video', 'self_deaf', 'afk', 'channel', 'requested_to_speak_at', 'suppress', ) def __init__(self, *, data: VoiceStatePayload, channel: Optional[VocalGuildChannel] = None): self.session_id: str = data.get('session_id') self._update(data, channel) def _update(self, data: VoiceStatePayload, channel: Optional[VocalGuildChannel]): self.self_mute: bool = data.get('self_mute', False) self.self_deaf: bool = data.get('self_deaf', False) self.self_stream: bool = data.get('self_stream', False) self.self_video: bool = data.get('self_video', False) self.afk: bool = data.get('suppress', False) self.mute: bool = data.get('mute', False) self.deaf: bool = data.get('deaf', False) self.suppress: bool = data.get('suppress', False) self.requested_to_speak_at: Optional[datetime.datetime] = utils.parse_time(data.get('request_to_speak_timestamp')) self.channel: Optional[VocalGuildChannel] = channel def __repr__(self) -> str: attrs = [ ('self_mute', self.self_mute), ('self_deaf', self.self_deaf), ('self_stream', self.self_stream), ('suppress', self.suppress), ('requested_to_speak_at', self.requested_to_speak_at), ('channel', self.channel), ] inner = ' '.join('%s=%r' % t for t in attrs) return f'<{self.__class__.__name__} {inner}>' 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): # We want sphinx to properly show coroutine functions as coroutines if inspect.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) func = utils.copy_doc(value)(func) setattr(cls, attr, func) return cls M = TypeVar('M', bound='Member') @flatten_user class Member(discord.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 :issue:`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', ) if TYPE_CHECKING: name: str id: int 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): 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, ...] = tuple() self.nick: Optional[str] = data.get('nick', None) self.pending: bool = data.get('pending', False) self._avatar: Optional[str] = data.get('avatar') def __str__(self) -> str: return str(self._user) def __repr__(self) -> str: return ( f'<Member id={self._user.id} name={self._user.name!r} discriminator={self._user.discriminator!r}' 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) @classmethod def _from_message(cls: Type[M], *, message: Message, data: MemberPayload) -> M: 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) @classmethod def _try_upgrade(cls: Type[M], *, data: UserWithMemberPayload, guild: Guild, state: ConnectionState) -> Union[User, M]: # 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 @classmethod def _copy(cls: Type[M], member: M) -> M: self: M = 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 # Reference will not be copied unless necessary by PRESENCE_UPDATE # See below self._user = member._user return self async def _get_channel(self): ch = await self.create_dm() return ch def _update(self, data: MemberPayload) -> None: # the nickname change is optional, # if it isn't in the payload then it didn't change try: self.nick = data['nick'] except KeyError: pass try: self.pending = data['pending'] except KeyError: pass self.premium_since = utils.parse_time(data.get('premium_since')) self._roles = utils.SnowflakeList(map(int, data['roles'])) self._avatar = data.get('avatar') def _presence_update(self, data: PartialPresenceUpdate, user: UserPayload) -> Optional[Tuple[User, User]]: self.activities = tuple(map(create_activity, 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 @property def status(self) -> Status: """:class:`Status`: 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]) @property def raw_status(self) -> str: """:class:`str`: The member's overall status as a string value. .. versionadded:: 1.5 """ return self._client_status[None] @status.setter def status(self, value: Status) -> None: # internal use only self._client_status[None] = str(value) @property 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')) @property 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')) @property 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 @property 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() @property 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 @property 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 @property def mention(self) -> str: """:class:`str`: Returns a string that allows you to mention the member.""" if self.nick: return f'<@!{self._user.id}>' return f'<@{self._user.id}>' @property 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 @property 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 @property 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) @property 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 :issue:`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] 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) @property 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) @property 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 @property def voice(self) -> Optional[VoiceState]: """Optional[:class:`VoiceState`]: Returns the member's current voice state.""" return self.guild._voice_state_for(self._user.id) async def ban( self, *, delete_message_days: Literal[0, 1, 2, 3, 4, 5, 6, 7] = 1, reason: Optional[str] = None, ) -> None: """|coro| Bans this member. Equivalent to :meth:`Guild.ban`. """ await self.guild.ban(self, reason=reason, 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 edit( self, *, nick: Optional[str] = MISSING, mute: bool = MISSING, deafen: bool = MISSING, suppress: bool = MISSING, roles: List[discord.abc.Snowflake] = MISSING, voice_channel: Optional[VocalGuildChannel] = MISSING, reason: Optional[str] = None, ) -> 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` | +---------------+--------------------------------------+ 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. 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: voice_state_payload = { 'channel_id': self.voice.channel.id, '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'] = datetime.datetime.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 payload: data = await http.edit_member(guild_id, self.id, reason=reason, **payload) return Member(data=data, guild=self.guild, state=self._state) 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, 'request_to_speak_timestamp': datetime.datetime.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: 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 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 = 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 = [Object(id=r.id) for r in self.roles[1:]] # remove @everyone for role in roles: try: new_roles.remove(Object(id=role.id)) except ValueError: pass 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
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/member.py
member.py
from __future__ import annotations from typing import Callable, Any, ClassVar, Dict, Iterator, Set, TYPE_CHECKING, Tuple, Type, TypeVar, Optional from .flags import BaseFlags, flag_value, fill_with_flags, alias_flag_value __all__ = ( 'Permissions', 'PermissionOverwrite', ) # A permission alias works like a regular flag but is marked # So the PermissionOverwrite knows to work with it 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 P = TypeVar('P', bound='Permissions') @fill_with_flags() 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): 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 else: 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 else: 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 @classmethod def none(cls: Type[P]) -> P: """A factory method that creates a :class:`Permissions` with all permissions set to ``False``.""" return cls(0) @classmethod def all(cls: Type[P]) -> P: """A factory method that creates a :class:`Permissions` with all permissions set to ``True``. """ return cls(0b111111111111111111111111111111111111111) @classmethod def all_channel(cls: Type[P]) -> P: """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) @classmethod def general(cls: Type[P]) -> P: """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) @classmethod def membership(cls: Type[P]) -> P: """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) @classmethod def text(cls: Type[P]) -> P: """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) @classmethod def voice(cls: Type[P]) -> P: """A factory method that creates a :class:`Permissions` with all "Voice" permissions from the official Discord UI set to ``True``.""" return cls(0b00000011111100000000001100000000) @classmethod def stage(cls: Type[P]) -> P: """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) @classmethod def stage_moderator(cls: Type[P]) -> P: """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) @classmethod def advanced(cls: Type[P]) -> P: """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 @flag_value def create_instant_invite(self) -> int: """:class:`bool`: Returns ``True`` if the user can create instant invites.""" return 1 << 0 @flag_value def kick_members(self) -> int: """:class:`bool`: Returns ``True`` if the user can kick users from the guild.""" return 1 << 1 @flag_value def ban_members(self) -> int: """:class:`bool`: Returns ``True`` if a user can ban users from the guild.""" return 1 << 2 @flag_value 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 @flag_value 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 @flag_value def manage_guild(self) -> int: """:class:`bool`: Returns ``True`` if a user can edit guild properties.""" return 1 << 5 @flag_value def add_reactions(self) -> int: """:class:`bool`: Returns ``True`` if a user can add reactions to messages.""" return 1 << 6 @flag_value def view_audit_log(self) -> int: """:class:`bool`: Returns ``True`` if a user can view the guild's audit log.""" return 1 << 7 @flag_value def priority_speaker(self) -> int: """:class:`bool`: Returns ``True`` if a user can be more easily heard while talking.""" return 1 << 8 @flag_value def stream(self) -> int: """:class:`bool`: Returns ``True`` if a user can stream in a voice channel.""" return 1 << 9 @flag_value def read_messages(self) -> int: """:class:`bool`: Returns ``True`` if a user can read messages from all or specific text channels.""" return 1 << 10 @make_permission_alias('read_messages') def view_channel(self) -> int: """:class:`bool`: An alias for :attr:`read_messages`. .. versionadded:: 1.3 """ return 1 << 10 @flag_value def send_messages(self) -> int: """:class:`bool`: Returns ``True`` if a user can send messages from all or specific text channels.""" return 1 << 11 @flag_value 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 @flag_value 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 @flag_value def embed_links(self) -> int: """:class:`bool`: Returns ``True`` if a user's messages will automatically be embedded by Discord.""" return 1 << 14 @flag_value def attach_files(self) -> int: """:class:`bool`: Returns ``True`` if a user can send files in their messages.""" return 1 << 15 @flag_value def read_message_history(self) -> int: """:class:`bool`: Returns ``True`` if a user can read a text channel's previous messages.""" return 1 << 16 @flag_value 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 @flag_value def external_emojis(self) -> int: """:class:`bool`: Returns ``True`` if a user can use emojis from other guilds.""" return 1 << 18 @make_permission_alias('external_emojis') def use_external_emojis(self) -> int: """:class:`bool`: An alias for :attr:`external_emojis`. .. versionadded:: 1.3 """ return 1 << 18 @flag_value 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 @flag_value def connect(self) -> int: """:class:`bool`: Returns ``True`` if a user can connect to a voice channel.""" return 1 << 20 @flag_value def speak(self) -> int: """:class:`bool`: Returns ``True`` if a user can speak in a voice channel.""" return 1 << 21 @flag_value def mute_members(self) -> int: """:class:`bool`: Returns ``True`` if a user can mute other users.""" return 1 << 22 @flag_value def deafen_members(self) -> int: """:class:`bool`: Returns ``True`` if a user can deafen other users.""" return 1 << 23 @flag_value def move_members(self) -> int: """:class:`bool`: Returns ``True`` if a user can move users between other voice channels.""" return 1 << 24 @flag_value def use_voice_activation(self) -> int: """:class:`bool`: Returns ``True`` if a user can use voice activation in voice channels.""" return 1 << 25 @flag_value def change_nickname(self) -> int: """:class:`bool`: Returns ``True`` if a user can change their nickname in the guild.""" return 1 << 26 @flag_value def manage_nicknames(self) -> int: """:class:`bool`: Returns ``True`` if a user can change other user's nickname in the guild.""" return 1 << 27 @flag_value 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 @make_permission_alias('manage_roles') def manage_permissions(self) -> int: """:class:`bool`: An alias for :attr:`manage_roles`. .. versionadded:: 1.3 """ return 1 << 28 @flag_value def manage_webhooks(self) -> int: """:class:`bool`: Returns ``True`` if a user can create, edit, or delete webhooks.""" return 1 << 29 @flag_value def manage_emojis(self) -> int: """:class:`bool`: Returns ``True`` if a user can create, edit, or delete emojis.""" return 1 << 30 @make_permission_alias('manage_emojis') def manage_emojis_and_stickers(self) -> int: """:class:`bool`: An alias for :attr:`manage_emojis`. .. versionadded:: 2.0 """ return 1 << 30 @flag_value def use_slash_commands(self) -> int: """:class:`bool`: Returns ``True`` if a user can use slash commands. .. versionadded:: 1.7 """ return 1 << 31 @flag_value 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 @flag_value def manage_events(self) -> int: """:class:`bool`: Returns ``True`` if a user can manage guild events. .. versionadded:: 2.0 """ return 1 << 33 @flag_value def manage_threads(self) -> int: """:class:`bool`: Returns ``True`` if a user can manage threads. .. versionadded:: 2.0 """ return 1 << 34 @flag_value def create_public_threads(self) -> int: """:class:`bool`: Returns ``True`` if a user can create public threads. .. versionadded:: 2.0 """ return 1 << 35 @flag_value def create_private_threads(self) -> int: """:class:`bool`: Returns ``True`` if a user can create private threads. .. versionadded:: 2.0 """ return 1 << 36 @flag_value def external_stickers(self) -> int: """:class:`bool`: Returns ``True`` if a user can use stickers from other guilds. .. versionadded:: 2.0 """ return 1 << 37 @make_permission_alias('external_stickers') def use_external_stickers(self) -> int: """:class:`bool`: An alias for :attr:`external_stickers`. .. versionadded:: 2.0 """ return 1 << 37 @flag_value def send_messages_in_threads(self) -> int: """:class:`bool`: Returns ``True`` if a user can send messages in threads. .. versionadded:: 2.0 """ return 1 << 38 PO = TypeVar('PO', bound='PermissionOverwrite') 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): self._set(x, value) prop = property(getter, setter) setattr(cls, name, prop) cls.PURE_FLAGS = cls.VALID_NAMES - aliases return cls @_augment_from_permissions 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] def __init__(self, **kwargs: Optional[bool]): 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 @classmethod def from_pair(cls: Type[PO], allow: Permissions, deny: Permissions) -> PO: """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)
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/permissions.py
permissions.py
from __future__ import annotations from typing import List, TYPE_CHECKING, Optional from . import utils from .asset import Asset if TYPE_CHECKING: from .guild import Guild from .types.appinfo import ( AppInfo as AppInfoPayload, PartialAppInfo as PartialAppInfoPayload, Team as TeamPayload, ) from .user import User from .state import ConnectionState __all__ = ( 'AppInfo', 'PartialAppInfo', ) class AppInfo: """Represents the application info for the bot provided by Discord. Attributes ------------- id: :class:`int` The application ID. name: :class:`str` The application name. owner: :class:`User` The application owner. team: Optional[:class:`Team`] The application's team. .. versionadded:: 1.3 description: :class:`str` The application description. bot_public: :class:`bool` Whether the bot can be invited by anyone or if it is locked to the application owner. bot_require_code_grant: :class:`bool` Whether the bot requires the completion of the full oauth2 code grant flow to join. rpc_origins: Optional[List[:class:`str`]] A list of RPC origin URLs, if RPC is enabled. summary: :class:`str` If this application is a game sold on Discord, this field will be the summary field for the store page of its primary SKU. .. versionadded:: 1.3 verify_key: :class:`str` The hex encoded key for verification in interactions and the GameSDK's `GetTicket <https://discord.com/developers/docs/game-sdk/applications#getticket>`_. .. versionadded:: 1.3 guild_id: Optional[:class:`int`] If this application is a game sold on Discord, this field will be the guild to which it has been linked to. .. versionadded:: 1.3 primary_sku_id: Optional[:class:`int`] If this application is a game sold on Discord, this field will be the id of the "Game SKU" that is created, if it exists. .. versionadded:: 1.3 slug: Optional[:class:`str`] If this application is a game sold on Discord, this field will be the URL slug that links to the store page. .. versionadded:: 1.3 terms_of_service_url: Optional[:class:`str`] The application's terms of service URL, if set. .. versionadded:: 2.0 privacy_policy_url: Optional[:class:`str`] The application's privacy policy URL, if set. .. versionadded:: 2.0 """ __slots__ = ( '_state', 'description', 'id', 'name', 'rpc_origins', 'bot_public', 'bot_require_code_grant', 'owner', '_icon', 'summary', 'verify_key', 'team', 'guild_id', 'primary_sku_id', 'slug', '_cover_image', 'terms_of_service_url', 'privacy_policy_url', ) def __init__(self, state: ConnectionState, data: AppInfoPayload): from .team import Team self._state: ConnectionState = state self.id: int = int(data['id']) self.name: str = data['name'] self.description: str = data['description'] self._icon: Optional[str] = data['icon'] self.rpc_origins: List[str] = data['rpc_origins'] self.bot_public: bool = data['bot_public'] self.bot_require_code_grant: bool = data['bot_require_code_grant'] self.owner: User = state.create_user(data['owner']) team: Optional[TeamPayload] = data.get('team') self.team: Optional[Team] = Team(state, team) if team else None self.summary: str = data['summary'] self.verify_key: str = data['verify_key'] self.guild_id: Optional[int] = utils._get_as_snowflake(data, 'guild_id') self.primary_sku_id: Optional[int] = utils._get_as_snowflake(data, 'primary_sku_id') self.slug: Optional[str] = data.get('slug') self._cover_image: Optional[str] = data.get('cover_image') self.terms_of_service_url: Optional[str] = data.get('terms_of_service_url') self.privacy_policy_url: Optional[str] = data.get('privacy_policy_url') def __repr__(self) -> str: return ( f'<{self.__class__.__name__} id={self.id} name={self.name!r} ' f'description={self.description!r} public={self.bot_public} ' f'owner={self.owner!r}>' ) @property def icon(self) -> Optional[Asset]: """Optional[:class:`.Asset`]: Retrieves the application's icon asset, if any.""" if self._icon is None: return None return Asset._from_icon(self._state, self.id, self._icon, path='app') @property def cover_image(self) -> Optional[Asset]: """Optional[:class:`.Asset`]: Retrieves the cover image on a store embed, if any. This is only available if the application is a game sold on Discord. """ if self._cover_image is None: return None return Asset._from_cover_image(self._state, self.id, self._cover_image) @property def guild(self) -> Optional[Guild]: """Optional[:class:`Guild`]: If this application is a game sold on Discord, this field will be the guild to which it has been linked .. versionadded:: 1.3 """ return self._state._get_guild(self.guild_id) class PartialAppInfo: """Represents a partial AppInfo given by :func:`~discord.abc.GuildChannel.create_invite` .. versionadded:: 2.0 Attributes ------------- id: :class:`int` The application ID. name: :class:`str` The application name. description: :class:`str` The application description. rpc_origins: Optional[List[:class:`str`]] A list of RPC origin URLs, if RPC is enabled. summary: :class:`str` If this application is a game sold on Discord, this field will be the summary field for the store page of its primary SKU. verify_key: :class:`str` The hex encoded key for verification in interactions and the GameSDK's `GetTicket <https://discord.com/developers/docs/game-sdk/applications#getticket>`_. terms_of_service_url: Optional[:class:`str`] The application's terms of service URL, if set. privacy_policy_url: Optional[:class:`str`] The application's privacy policy URL, if set. """ __slots__ = ('_state', 'id', 'name', 'description', 'rpc_origins', 'summary', 'verify_key', 'terms_of_service_url', 'privacy_policy_url', '_icon') def __init__(self, *, state: ConnectionState, data: PartialAppInfoPayload): self._state: ConnectionState = state self.id: int = int(data['id']) self.name: str = data['name'] self._icon: Optional[str] = data.get('icon') self.description: str = data['description'] self.rpc_origins: Optional[List[str]] = data.get('rpc_origins') self.summary: str = data['summary'] self.verify_key: str = data['verify_key'] self.terms_of_service_url: Optional[str] = data.get('terms_of_service_url') self.privacy_policy_url: Optional[str] = data.get('privacy_policy_url') def __repr__(self) -> str: return f'<{self.__class__.__name__} id={self.id} name={self.name!r} description={self.description!r}>' @property def icon(self) -> Optional[Asset]: """Optional[:class:`.Asset`]: Retrieves the application's icon asset, if any.""" if self._icon is None: return None return Asset._from_icon(self._state, self.id, self._icon, path='app')
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/appinfo.py
appinfo.py
from __future__ import annotations from typing import Any, Dict, List, Optional, TYPE_CHECKING, Tuple, Union import asyncio from . import utils from .enums import try_enum, InteractionType, InteractionResponseType from .errors import InteractionResponded, HTTPException, ClientException from .channel import PartialMessageable, ChannelType from .user import User from .member import Member from .message import Message, Attachment from .object import Object from .permissions import Permissions from .webhook.async_ import async_context, Webhook, handle_message_parameters __all__ = ( 'Interaction', 'InteractionMessage', 'InteractionResponse', ) if TYPE_CHECKING: from .types.interactions import ( Interaction as InteractionPayload, InteractionData, ) from .guild import Guild from .state import ConnectionState from .file import File from .mentions import AllowedMentions from aiohttp import ClientSession from .embeds import Embed from .ui.view import View from .channel import VoiceChannel, StageChannel, TextChannel, CategoryChannel, StoreChannel, PartialMessageable from .threads import Thread InteractionChannel = Union[ VoiceChannel, StageChannel, TextChannel, CategoryChannel, StoreChannel, Thread, PartialMessageable ] MISSING: Any = utils.MISSING class Interaction: """Represents a Discord interaction. An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components. .. versionadded:: 2.0 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. 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. """ __slots__: Tuple[str, ...] = ( 'id', 'type', 'guild_id', 'channel_id', 'data', 'application_id', 'message', 'user', 'token', 'version', '_permissions', '_state', '_session', '_original_message', '_cs_response', '_cs_followup', '_cs_channel', ) def __init__(self, *, data: InteractionPayload, state: ConnectionState): self._state: ConnectionState = state self._session: ClientSession = state.http._HTTPClient__session self._original_message: Optional[InteractionMessage] = None self._from_data(data) def _from_data(self, data: InteractionPayload): 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.message: Optional[Message] try: self.message = Message(state=self._state, channel=self.channel, data=data['message']) # type: ignore except KeyError: self.message = None self.user: Optional[Union[User, Member]] = None 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'] # type: ignore except KeyError: pass else: self.user = Member(state=self._state, guild=guild, data=member) # type: ignore self._permissions = int(member.get('permissions', 0)) else: try: self.user = User(state=self._state, data=data['user']) except KeyError: pass @property 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) @utils.cached_slot_property('_cs_channel') 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 @property 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) @utils.cached_slot_property('_cs_response') 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) @utils.cached_slot_property('_cs_followup') 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, 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. allowed_mentions: :class:`AllowedMentions` Controls the mentions being processed in this message. See :meth:`.abc.Messageable.send` for more information. view: Optional[:class:`~discord.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. TypeError 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, 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(): self._state.store_view(view, message.id) return message async def delete_original_message(self) -> 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. Raises ------- HTTPException Deleting the message failed. Forbidden Deleted a message that is not yours. """ adapter = async_context.get() await adapter.delete_original_interaction_response( self.application_id, self.token, session=self._session, ) class InteractionResponse: """Represents a Discord interaction response. This type can be accessed through :attr:`Interaction.response`. .. versionadded:: 2.0 """ __slots__: Tuple[str, ...] = ( '_responded', '_parent', ) def __init__(self, parent: Interaction): self._parent: Interaction = parent self._responded: bool = False def is_done(self) -> bool: """:class:`bool`: Indicates whether an interaction response has been done before. An interaction can only be responded to once. """ return self._responded async def defer(self, *, ephemeral: bool = False) -> None: """|coro| Defers the interaction response. This is typically used when the interaction is acknowledged and a secondary action will be done later. Parameters ----------- ephemeral: :class:`bool` Indicates whether the deferred message will eventually be ephemeral. This only applies for interactions of type :attr:`InteractionType.application_command`. Raises ------- HTTPException Deferring the interaction failed. InteractionResponded This interaction has already been responded to before. """ if self._responded: raise InteractionResponded(self._parent) defer_type: int = 0 data: Optional[Dict[str, Any]] = None parent = self._parent if parent.type is InteractionType.component: defer_type = InteractionResponseType.deferred_message_update.value elif parent.type is InteractionType.application_command: defer_type = InteractionResponseType.deferred_channel_message.value if ephemeral: data = {'flags': 64} if defer_type: adapter = async_context.get() await adapter.create_interaction_response( parent.id, parent.token, session=parent._session, type=defer_type, data=data ) self._responded = True async def pong(self) -> None: """|coro| Pongs the ping interaction. This should rarely be used. Raises ------- HTTPException Ponging the interaction failed. InteractionResponded This interaction has already been responded to before. """ if self._responded: raise InteractionResponded(self._parent) parent = self._parent if parent.type is InteractionType.ping: adapter = async_context.get() await adapter.create_interaction_response( parent.id, parent.token, session=parent._session, type=InteractionResponseType.pong.value ) self._responded = True async def send_message( self, content: Optional[Any] = None, *, embed: Embed = MISSING, embeds: List[Embed] = MISSING, view: View = MISSING, tts: bool = False, ephemeral: bool = False, ) -> None: """|coro| Responds to this interaction by sending a message. Parameters ----------- content: Optional[:class:`str`] The content of the message to send. embeds: List[:class:`Embed`] A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the ``embed`` parameter. embed: :class:`Embed` The rich embed for the content to send. This cannot be mixed with ``embeds`` parameter. tts: :class:`bool` Indicates if the message should be sent using text-to-speech. view: :class:`discord.ui.View` The view to send with the message. ephemeral: :class:`bool` Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes. Raises ------- HTTPException Sending the message failed. TypeError You specified both ``embed`` and ``embeds``. ValueError The length of ``embeds`` was invalid. InteractionResponded This interaction has already been responded to before. """ if self._responded: raise InteractionResponded(self._parent) payload: Dict[str, Any] = { 'tts': tts, } if embed is not MISSING and embeds is not MISSING: raise TypeError('cannot mix embed and embeds keyword arguments') if embed is not MISSING: embeds = [embed] if embeds: if len(embeds) > 10: raise ValueError('embeds cannot exceed maximum of 10 elements') payload['embeds'] = [e.to_dict() for e in embeds] if content is not None: payload['content'] = str(content) if ephemeral: payload['flags'] = 64 if view is not MISSING: payload['components'] = view.to_components() parent = self._parent adapter = async_context.get() await adapter.create_interaction_response( parent.id, parent.token, session=parent._session, type=InteractionResponseType.channel_message.value, data=payload, ) if view is not MISSING: if ephemeral and view.timeout is None: view.timeout = 15 * 60.0 self._parent._state.store_view(view) self._responded = True async def edit_message( self, *, content: Optional[Any] = MISSING, embed: Optional[Embed] = MISSING, embeds: List[Embed] = MISSING, attachments: List[Attachment] = MISSING, view: Optional[View] = MISSING, ) -> None: """|coro| Responds to this interaction by editing the original message of a component interaction. Parameters ----------- content: Optional[:class:`str`] The new content to replace the message with. ``None`` removes the content. 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. attachments: List[:class:`Attachment`] A list of attachments to keep in the message. If ``[]`` is passed then all attachments are removed. view: Optional[:class:`~discord.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. TypeError You specified both ``embed`` and ``embeds``. InteractionResponded This interaction has already been responded to before. """ if self._responded: raise InteractionResponded(self._parent) parent = self._parent msg = parent.message state = parent._state message_id = msg.id if msg else None if parent.type is not InteractionType.component: return payload = {} if content is not MISSING: if content is None: payload['content'] = None else: payload['content'] = str(content) if embed is not MISSING and embeds is not MISSING: raise TypeError('cannot mix both embed and embeds keyword arguments') if embed is not MISSING: if embed is None: embeds = [] else: embeds = [embed] if embeds is not MISSING: payload['embeds'] = [e.to_dict() for e in embeds] if attachments is not MISSING: payload['attachments'] = [a.to_dict() for a in attachments] if view is not MISSING: state.prevent_view_updates_for(message_id) if view is None: payload['components'] = [] else: payload['components'] = view.to_components() adapter = async_context.get() await adapter.create_interaction_response( parent.id, parent.token, session=parent._session, type=InteractionResponseType.message_update.value, data=payload, ) if view and not view.is_finished(): state.store_view(view, message_id) self._responded = True class _InteractionMessageState: __slots__ = ('_parent', '_interaction') def __init__(self, interaction: Interaction, parent: ConnectionState): self._interaction: Interaction = interaction self._parent: ConnectionState = parent def _get_guild(self, guild_id): return self._parent._get_guild(guild_id) def store_user(self, data): return self._parent.store_user(data) def create_user(self, data): return self._parent.create_user(data) @property def http(self): return self._parent.http def __getattr__(self, attr): return getattr(self._parent, attr) class InteractionMessage(Message): """Represents the original interaction response message. This allows you to edit or delete the message associated with the interaction response. To retrieve this object see :meth:`Interaction.original_message`. This inherits from :class:`discord.Message` with changes to :meth:`edit` and :meth:`delete` to work. .. versionadded:: 2.0 """ __slots__ = () _state: _InteractionMessageState async def edit( self, content: Optional[str] = MISSING, embeds: List[Embed] = MISSING, embed: Optional[Embed] = MISSING, file: File = MISSING, files: List[File] = MISSING, view: Optional[View] = MISSING, allowed_mentions: Optional[AllowedMentions] = None, ) -> InteractionMessage: """|coro| Edits the message. 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. allowed_mentions: :class:`AllowedMentions` Controls the mentions being processed in this message. See :meth:`.abc.Messageable.send` for more information. view: Optional[:class:`~discord.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. TypeError You specified both ``embed`` and ``embeds`` or ``file`` and ``files`` ValueError The length of ``embeds`` was invalid. Returns --------- :class:`InteractionMessage` The newly edited message. """ return await self._state._interaction.edit_original_message( content=content, embeds=embeds, embed=embed, file=file, files=files, view=view, allowed_mentions=allowed_mentions, ) async def delete(self, *, delay: Optional[float] = None) -> None: """|coro| Deletes the message. 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 ------ 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 inner_call(delay: float = delay): await asyncio.sleep(delay) try: await self._state._interaction.delete_original_message() except HTTPException: pass asyncio.create_task(inner_call()) else: await self._state._interaction.delete_original_message()
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/interactions.py
interactions.py
from __future__ import annotations from typing import Literal, TYPE_CHECKING, List, Optional, Tuple, Type, Union import unicodedata from .mixins import Hashable from .asset import Asset, AssetMixin from .utils import cached_slot_property, find, snowflake_time, get, MISSING from .errors import InvalidData from .enums import StickerType, StickerFormatType, try_enum __all__ = ( 'StickerPack', 'StickerItem', 'Sticker', 'StandardSticker', 'GuildSticker', ) if TYPE_CHECKING: import datetime from .state import ConnectionState from .user import User from .guild import Guild from .types.sticker import ( StickerPack as StickerPackPayload, StickerItem as StickerItemPayload, Sticker as StickerPayload, StandardSticker as StandardStickerPayload, GuildSticker as GuildStickerPayload, ListPremiumStickerPacks as ListPremiumStickerPacksPayload, EditGuildSticker, ) class StickerPack(Hashable): """Represents a sticker pack. .. versionadded:: 2.0 .. container:: operations .. describe:: str(x) Returns the name of the sticker pack. .. describe:: x == y Checks if the sticker pack is equal to another sticker pack. .. describe:: x != y Checks if the sticker pack is not equal to another sticker pack. Attributes ----------- name: :class:`str` The name of the sticker pack. description: :class:`str` The description of the sticker pack. id: :class:`int` The id of the sticker pack. stickers: List[:class:`StandardSticker`] The stickers of this sticker pack. sku_id: :class:`int` The SKU ID of the sticker pack. cover_sticker_id: :class:`int` The ID of the sticker used for the cover of the sticker pack. cover_sticker: :class:`StandardSticker` The sticker used for the cover of the sticker pack. """ __slots__ = ( '_state', 'id', 'stickers', 'name', 'sku_id', 'cover_sticker_id', 'cover_sticker', 'description', '_banner', ) def __init__(self, *, state: ConnectionState, data: StickerPackPayload) -> None: self._state: ConnectionState = state self._from_data(data) def _from_data(self, data: StickerPackPayload) -> None: self.id: int = int(data['id']) stickers = data['stickers'] self.stickers: List[StandardSticker] = [StandardSticker(state=self._state, data=sticker) for sticker in stickers] self.name: str = data['name'] self.sku_id: int = int(data['sku_id']) self.cover_sticker_id: int = int(data['cover_sticker_id']) self.cover_sticker: StandardSticker = get(self.stickers, id=self.cover_sticker_id) # type: ignore self.description: str = data['description'] self._banner: int = int(data['banner_asset_id']) @property def banner(self) -> Asset: """:class:`Asset`: The banner asset of the sticker pack.""" return Asset._from_sticker_banner(self._state, self._banner) def __repr__(self) -> str: return f'<StickerPack id={self.id} name={self.name!r} description={self.description!r}>' def __str__(self) -> str: return self.name class _StickerTag(Hashable, AssetMixin): __slots__ = () id: int format: StickerFormatType async def read(self) -> bytes: """|coro| Retrieves the content of this sticker as a :class:`bytes` object. .. note:: Stickers that use the :attr:`StickerFormatType.lottie` format cannot be read. Raises ------ HTTPException Downloading the asset failed. NotFound The asset was deleted. TypeError The sticker is a lottie type. Returns ------- :class:`bytes` The content of the asset. """ if self.format is StickerFormatType.lottie: raise TypeError('Cannot read stickers of format "lottie".') return await super().read() class StickerItem(_StickerTag): """Represents a sticker item. .. versionadded:: 2.0 .. container:: operations .. describe:: str(x) Returns the name of the sticker item. .. describe:: x == y Checks if the sticker item is equal to another sticker item. .. describe:: x != y Checks if the sticker item is not equal to another sticker item. Attributes ----------- name: :class:`str` The sticker's name. id: :class:`int` The id of the sticker. format: :class:`StickerFormatType` The format for the sticker's image. url: :class:`str` The URL for the sticker's image. """ __slots__ = ('_state', 'name', 'id', 'format', 'url') def __init__(self, *, state: ConnectionState, data: StickerItemPayload): self._state: ConnectionState = state self.name: str = data['name'] self.id: int = int(data['id']) 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'<StickerItem id={self.id} name={self.name!r} format={self.format}>' def __str__(self) -> str: return self.name async def fetch(self) -> Union[Sticker, StandardSticker, GuildSticker]: """|coro| Attempts to retrieve the full sticker data of the sticker item. Raises -------- HTTPException Retrieving the sticker failed. Returns -------- Union[:class:`StandardSticker`, :class:`GuildSticker`] The retrieved sticker. """ data: StickerPayload = await self._state.http.get_sticker(self.id) cls, _ = _sticker_factory(data['type']) # type: ignore return cls(state=self._state, data=data) 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 @property 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}>' @cached_slot_property('_cs_guild') 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) 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 elif value == StickerType.guild: return GuildSticker, value else: return Sticker, value
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/sticker.py
sticker.py
import asyncio from collections import namedtuple, deque import concurrent.futures import logging import struct import sys import time import threading import traceback import zlib import aiohttp from . import utils from .activity import BaseActivity from .enums import SpeakingState from .errors import ConnectionClosed, InvalidArgument _log = logging.getLogger(__name__) __all__ = ( 'DiscordWebSocket', 'KeepAliveHandler', 'VoiceKeepAliveHandler', 'DiscordVoiceWebSocket', 'ReconnectWebSocket', ) class ReconnectWebSocket(Exception): """Signals to safely reconnect the websocket.""" def __init__(self, shard_id, *, resume=True): self.shard_id = shard_id self.resume = resume self.op = 'RESUME' if resume else 'IDENTIFY' class WebSocketClosure(Exception): """An exception to make up for the fact that aiohttp doesn't signal closure.""" pass EventListener = namedtuple('EventListener', 'predicate event result future') class GatewayRatelimiter: def __init__(self, count=110, per=60.0): # The default is 110 to give room for at least 10 heartbeats per minute self.max = count self.remaining = count self.window = 0.0 self.per = per self.lock = asyncio.Lock() self.shard_id = None def is_ratelimited(self): current = time.time() if current > self.window + self.per: return False return self.remaining == 0 def get_delay(self): current = time.time() if current > self.window + self.per: self.remaining = self.max if self.remaining == self.max: self.window = current if self.remaining == 0: return self.per - (current - self.window) self.remaining -= 1 if self.remaining == 0: self.window = current return 0.0 async def block(self): async with self.lock: delta = self.get_delay() if delta: _log.warning('WebSocket in shard ID %s is ratelimited, waiting %.2f seconds', self.shard_id, delta) await asyncio.sleep(delta) class KeepAliveHandler(threading.Thread): def __init__(self, *args, **kwargs): ws = kwargs.pop('ws', None) interval = kwargs.pop('interval', None) shard_id = kwargs.pop('shard_id', None) threading.Thread.__init__(self, *args, **kwargs) self.ws = ws self._main_thread_id = ws.thread_id self.interval = interval self.daemon = True self.shard_id = shard_id self.msg = 'Keeping shard ID %s websocket alive with sequence %s.' self.block_msg = 'Shard ID %s heartbeat blocked for more than %s seconds.' self.behind_msg = 'Can\'t keep up, shard ID %s websocket is %.1fs behind.' self._stop_ev = threading.Event() self._last_ack = time.perf_counter() self._last_send = time.perf_counter() self._last_recv = time.perf_counter() self.latency = float('inf') self.heartbeat_timeout = ws._max_heartbeat_timeout def run(self): while not self._stop_ev.wait(self.interval): if self._last_recv + self.heartbeat_timeout < time.perf_counter(): _log.warning("Shard ID %s has stopped responding to the gateway. Closing and restarting.", self.shard_id) coro = self.ws.close(4000) f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop) try: f.result() except Exception: _log.exception('An error occurred while stopping the gateway. Ignoring.') finally: self.stop() return data = self.get_payload() _log.debug(self.msg, self.shard_id, data['d']) coro = self.ws.send_heartbeat(data) f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop) try: # block until sending is complete total = 0 while True: try: f.result(10) break except concurrent.futures.TimeoutError: total += 10 try: frame = sys._current_frames()[self._main_thread_id] except KeyError: msg = self.block_msg else: stack = ''.join(traceback.format_stack(frame)) msg = f'{self.block_msg}\nLoop thread traceback (most recent call last):\n{stack}' _log.warning(msg, self.shard_id, total) except Exception: self.stop() else: self._last_send = time.perf_counter() def get_payload(self): return { 'op': self.ws.HEARTBEAT, 'd': self.ws.sequence } def stop(self): self._stop_ev.set() def tick(self): self._last_recv = time.perf_counter() def ack(self): ack_time = time.perf_counter() self._last_ack = ack_time self.latency = ack_time - self._last_send if self.latency > 10: _log.warning(self.behind_msg, self.shard_id, self.latency) class VoiceKeepAliveHandler(KeepAliveHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.recent_ack_latencies = deque(maxlen=20) self.msg = 'Keeping shard ID %s voice websocket alive with timestamp %s.' self.block_msg = 'Shard ID %s voice heartbeat blocked for more than %s seconds' self.behind_msg = 'High socket latency, shard ID %s heartbeat is %.1fs behind' def get_payload(self): return { 'op': self.ws.HEARTBEAT, 'd': int(time.time() * 1000) } def ack(self): ack_time = time.perf_counter() self._last_ack = ack_time self._last_recv = ack_time self.latency = ack_time - self._last_send self.recent_ack_latencies.append(self.latency) class DiscordClientWebSocketResponse(aiohttp.ClientWebSocketResponse): async def close(self, *, code: int = 4000, message: bytes = b'') -> bool: return await super().close(code=code, message=message) class DiscordWebSocket: """Implements a WebSocket for Discord's gateway v6. Attributes ----------- DISPATCH Receive only. Denotes an event to be sent to Discord, such as READY. HEARTBEAT When received tells Discord to keep the connection alive. When sent asks if your connection is currently alive. IDENTIFY Send only. Starts a new session. PRESENCE Send only. Updates your presence. VOICE_STATE Send only. Starts a new connection to a voice guild. VOICE_PING Send only. Checks ping time to a voice guild, do not use. RESUME Send only. Resumes an existing connection. RECONNECT Receive only. Tells the client to reconnect to a new gateway. REQUEST_MEMBERS Send only. Asks for the full member list of a guild. INVALIDATE_SESSION Receive only. Tells the client to optionally invalidate the session and IDENTIFY again. HELLO Receive only. Tells the client the heartbeat interval. HEARTBEAT_ACK Receive only. Confirms receiving of a heartbeat. Not having it implies a connection issue. GUILD_SYNC Send only. Requests a guild sync. gateway The gateway we are currently connected to. token The authentication token for discord. """ DISPATCH = 0 HEARTBEAT = 1 IDENTIFY = 2 PRESENCE = 3 VOICE_STATE = 4 VOICE_PING = 5 RESUME = 6 RECONNECT = 7 REQUEST_MEMBERS = 8 INVALIDATE_SESSION = 9 HELLO = 10 HEARTBEAT_ACK = 11 GUILD_SYNC = 12 def __init__(self, socket, *, loop): self.socket = socket self.loop = loop # an empty dispatcher to prevent crashes self._dispatch = lambda *args: None # generic event listeners self._dispatch_listeners = [] # the keep alive self._keep_alive = None self.thread_id = threading.get_ident() # ws related stuff self.session_id = None self.sequence = None self._zlib = zlib.decompressobj() self._buffer = bytearray() self._close_code = None self._rate_limiter = GatewayRatelimiter() @property def open(self): return not self.socket.closed def is_ratelimited(self): return self._rate_limiter.is_ratelimited() def debug_log_receive(self, data, /): self._dispatch('socket_raw_receive', data) def log_receive(self, _, /): pass @classmethod async def from_client(cls, client, *, initial=False, gateway=None, shard_id=None, session=None, sequence=None, resume=False): """Creates a main websocket for Discord from a :class:`Client`. This is for internal use only. """ gateway = gateway or await client.http.get_gateway() socket = await client.http.ws_connect(gateway) ws = cls(socket, loop=client.loop) # dynamically add attributes needed ws.token = client.http.token ws._connection = client._connection ws._discord_parsers = client._connection.parsers ws._dispatch = client.dispatch ws.gateway = gateway ws.call_hooks = client._connection.call_hooks ws._initial_identify = initial ws.shard_id = shard_id ws._rate_limiter.shard_id = shard_id ws.shard_count = client._connection.shard_count ws.session_id = session ws.sequence = sequence ws._max_heartbeat_timeout = client._connection.heartbeat_timeout if client._enable_debug_events: ws.send = ws.debug_send ws.log_receive = ws.debug_log_receive client._connection._update_references(ws) _log.debug('Created websocket connected to %s', gateway) # poll event for OP Hello await ws.poll_event() if not resume: await ws.identify() return ws await ws.resume() return ws def wait_for(self, event, predicate, result=None): """Waits for a DISPATCH'd event that meets the predicate. Parameters ----------- event: :class:`str` The event name in all upper case to wait for. predicate A function that takes a data parameter to check for event properties. The data parameter is the 'd' key in the JSON message. result A function that takes the same data parameter and executes to send the result to the future. If ``None``, returns the data. Returns -------- asyncio.Future A future to wait for. """ future = self.loop.create_future() entry = EventListener(event=event, predicate=predicate, result=result, future=future) self._dispatch_listeners.append(entry) return future async def identify(self): """Sends the IDENTIFY packet.""" payload = { 'op': self.IDENTIFY, 'd': { 'token': self.token, 'properties': { '$os': sys.platform, '$browser': 'discord.py', '$device': 'discord.py', '$referrer': '', '$referring_domain': '' }, 'compress': True, 'large_threshold': 250, 'v': 3 } } if self.shard_id is not None and self.shard_count is not None: payload['d']['shard'] = [self.shard_id, self.shard_count] state = self._connection if state._activity is not None or state._status is not None: payload['d']['presence'] = { 'status': state._status, 'game': state._activity, 'since': 0, 'afk': False } if state._intents is not None: payload['d']['intents'] = state._intents.value await self.call_hooks('before_identify', self.shard_id, initial=self._initial_identify) await self.send_as_json(payload) _log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id) async def resume(self): """Sends the RESUME packet.""" payload = { 'op': self.RESUME, 'd': { 'seq': self.sequence, 'session_id': self.session_id, 'token': self.token } } await self.send_as_json(payload) _log.info('Shard ID %s has sent the RESUME payload.', self.shard_id) async def received_message(self, msg, /): if type(msg) is bytes: self._buffer.extend(msg) if len(msg) < 4 or msg[-4:] != b'\x00\x00\xff\xff': return msg = self._zlib.decompress(self._buffer) msg = msg.decode('utf-8') self._buffer = bytearray() self.log_receive(msg) msg = utils._from_json(msg) _log.debug('For Shard ID %s: WebSocket Event: %s', self.shard_id, msg) event = msg.get('t') if event: self._dispatch('socket_event_type', event) op = msg.get('op') data = msg.get('d') seq = msg.get('s') if seq is not None: self.sequence = seq if self._keep_alive: self._keep_alive.tick() if op != self.DISPATCH: if op == self.RECONNECT: # "reconnect" can only be handled by the Client # so we terminate our connection and raise an # internal exception signalling to reconnect. _log.debug('Received RECONNECT opcode.') await self.close() raise ReconnectWebSocket(self.shard_id) if op == self.HEARTBEAT_ACK: if self._keep_alive: self._keep_alive.ack() return if op == self.HEARTBEAT: if self._keep_alive: beat = self._keep_alive.get_payload() await self.send_as_json(beat) return if op == self.HELLO: interval = data['heartbeat_interval'] / 1000.0 self._keep_alive = KeepAliveHandler(ws=self, interval=interval, shard_id=self.shard_id) # send a heartbeat immediately await self.send_as_json(self._keep_alive.get_payload()) self._keep_alive.start() return if op == self.INVALIDATE_SESSION: if data is True: await self.close() raise ReconnectWebSocket(self.shard_id) self.sequence = None self.session_id = None _log.info('Shard ID %s session has been invalidated.', self.shard_id) await self.close(code=1000) raise ReconnectWebSocket(self.shard_id, resume=False) _log.warning('Unknown OP code %s.', op) return if event == 'READY': self._trace = trace = data.get('_trace', []) self.sequence = msg['s'] self.session_id = data['session_id'] # pass back shard ID to ready handler data['__shard_id__'] = self.shard_id _log.info('Shard ID %s has connected to Gateway: %s (Session ID: %s).', self.shard_id, ', '.join(trace), self.session_id) elif event == 'RESUMED': self._trace = trace = data.get('_trace', []) # pass back the shard ID to the resumed handler data['__shard_id__'] = self.shard_id _log.info('Shard ID %s has successfully RESUMED session %s under trace %s.', self.shard_id, self.session_id, ', '.join(trace)) try: func = self._discord_parsers[event] except KeyError: _log.debug('Unknown event %s.', event) else: func(data) # remove the dispatched listeners removed = [] for index, entry in enumerate(self._dispatch_listeners): if entry.event != event: continue future = entry.future if future.cancelled(): removed.append(index) continue try: valid = entry.predicate(data) except Exception as exc: future.set_exception(exc) removed.append(index) else: if valid: ret = data if entry.result is None else entry.result(data) future.set_result(ret) removed.append(index) for index in reversed(removed): del self._dispatch_listeners[index] @property def latency(self): """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.""" heartbeat = self._keep_alive return float('inf') if heartbeat is None else heartbeat.latency def _can_handle_close(self): code = self._close_code or self.socket.close_code return code not in (1000, 4004, 4010, 4011, 4012, 4013, 4014) async def poll_event(self): """Polls for a DISPATCH event and handles the general gateway loop. Raises ------ ConnectionClosed The websocket connection was terminated for unhandled reasons. """ try: msg = await self.socket.receive(timeout=self._max_heartbeat_timeout) if msg.type is aiohttp.WSMsgType.TEXT: await self.received_message(msg.data) elif msg.type is aiohttp.WSMsgType.BINARY: await self.received_message(msg.data) elif msg.type is aiohttp.WSMsgType.ERROR: _log.debug('Received %s', msg) raise msg.data elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSING, aiohttp.WSMsgType.CLOSE): _log.debug('Received %s', msg) raise WebSocketClosure except (asyncio.TimeoutError, WebSocketClosure) as e: # Ensure the keep alive handler is closed if self._keep_alive: self._keep_alive.stop() self._keep_alive = None if isinstance(e, asyncio.TimeoutError): _log.info('Timed out receiving packet. Attempting a reconnect.') raise ReconnectWebSocket(self.shard_id) from None code = self._close_code or self.socket.close_code if self._can_handle_close(): _log.info('Websocket closed with %s, attempting a reconnect.', code) raise ReconnectWebSocket(self.shard_id) from None else: _log.info('Websocket closed with %s, cannot reconnect.', code) raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None async def debug_send(self, data, /): await self._rate_limiter.block() self._dispatch('socket_raw_send', data) await self.socket.send_str(data) async def send(self, data, /): await self._rate_limiter.block() await self.socket.send_str(data) async def send_as_json(self, data): try: await self.send(utils._to_json(data)) except RuntimeError as exc: if not self._can_handle_close(): raise ConnectionClosed(self.socket, shard_id=self.shard_id) from exc async def send_heartbeat(self, data): # This bypasses the rate limit handling code since it has a higher priority try: await self.socket.send_str(utils._to_json(data)) except RuntimeError as exc: if not self._can_handle_close(): raise ConnectionClosed(self.socket, shard_id=self.shard_id) from exc async def change_presence(self, *, activity=None, status=None, since=0.0): if activity is not None: if not isinstance(activity, BaseActivity): raise InvalidArgument('activity must derive from BaseActivity.') activity = [activity.to_dict()] else: activity = [] if status == 'idle': since = int(time.time() * 1000) payload = { 'op': self.PRESENCE, 'd': { 'activities': activity, 'afk': False, 'since': since, 'status': status } } sent = utils._to_json(payload) _log.debug('Sending "%s" to change status', sent) await self.send(sent) async def request_chunks(self, guild_id, query=None, *, limit, user_ids=None, presences=False, nonce=None): payload = { 'op': self.REQUEST_MEMBERS, 'd': { 'guild_id': guild_id, 'presences': presences, 'limit': limit } } if nonce: payload['d']['nonce'] = nonce if user_ids: payload['d']['user_ids'] = user_ids if query is not None: payload['d']['query'] = query await self.send_as_json(payload) async def voice_state(self, guild_id, channel_id, self_mute=False, self_deaf=False): payload = { 'op': self.VOICE_STATE, 'd': { 'guild_id': guild_id, 'channel_id': channel_id, 'self_mute': self_mute, 'self_deaf': self_deaf } } _log.debug('Updating our voice state to %s.', payload) await self.send_as_json(payload) async def close(self, code=4000): if self._keep_alive: self._keep_alive.stop() self._keep_alive = None self._close_code = code await self.socket.close(code=code) class DiscordVoiceWebSocket: """Implements the websocket protocol for handling voice connections. Attributes ----------- IDENTIFY Send only. Starts a new voice session. SELECT_PROTOCOL Send only. Tells discord what encryption mode and how to connect for voice. READY Receive only. Tells the websocket that the initial connection has completed. HEARTBEAT Send only. Keeps your websocket connection alive. SESSION_DESCRIPTION Receive only. Gives you the secret key required for voice. SPEAKING Send only. Notifies the client if you are currently speaking. HEARTBEAT_ACK Receive only. Tells you your heartbeat has been acknowledged. RESUME Sent only. Tells the client to resume its session. HELLO Receive only. Tells you that your websocket connection was acknowledged. RESUMED Sent only. Tells you that your RESUME request has succeeded. CLIENT_CONNECT Indicates a user has connected to voice. CLIENT_DISCONNECT Receive only. Indicates a user has disconnected from voice. """ IDENTIFY = 0 SELECT_PROTOCOL = 1 READY = 2 HEARTBEAT = 3 SESSION_DESCRIPTION = 4 SPEAKING = 5 HEARTBEAT_ACK = 6 RESUME = 7 HELLO = 8 RESUMED = 9 CLIENT_CONNECT = 12 CLIENT_DISCONNECT = 13 def __init__(self, socket, loop, *, hook=None): self.ws = socket self.loop = loop self._keep_alive = None self._close_code = None self.secret_key = None if hook: self._hook = hook async def _hook(self, *args): pass async def send_as_json(self, data): _log.debug('Sending voice websocket frame: %s.', data) await self.ws.send_str(utils._to_json(data)) send_heartbeat = send_as_json async def resume(self): state = self._connection payload = { 'op': self.RESUME, 'd': { 'token': state.token, 'server_id': str(state.server_id), 'session_id': state.session_id } } await self.send_as_json(payload) async def identify(self): state = self._connection payload = { 'op': self.IDENTIFY, 'd': { 'server_id': str(state.server_id), 'user_id': str(state.user.id), 'session_id': state.session_id, 'token': state.token } } await self.send_as_json(payload) @classmethod async def from_client(cls, client, *, resume=False, hook=None): """Creates a voice websocket for the :class:`VoiceClient`.""" gateway = 'wss://' + client.endpoint + '/?v=4' http = client._state.http socket = await http.ws_connect(gateway, compress=15) ws = cls(socket, loop=client.loop, hook=hook) ws.gateway = gateway ws._connection = client ws._max_heartbeat_timeout = 60.0 ws.thread_id = threading.get_ident() if resume: await ws.resume() else: await ws.identify() return ws async def select_protocol(self, ip, port, mode): payload = { 'op': self.SELECT_PROTOCOL, 'd': { 'protocol': 'udp', 'data': { 'address': ip, 'port': port, 'mode': mode } } } await self.send_as_json(payload) async def client_connect(self): payload = { 'op': self.CLIENT_CONNECT, 'd': { 'audio_ssrc': self._connection.ssrc } } await self.send_as_json(payload) async def speak(self, state=SpeakingState.voice): payload = { 'op': self.SPEAKING, 'd': { 'speaking': int(state), 'delay': 0 } } await self.send_as_json(payload) async def received_message(self, msg): _log.debug('Voice websocket frame received: %s', msg) op = msg['op'] data = msg.get('d') if op == self.READY: await self.initial_connection(data) elif op == self.HEARTBEAT_ACK: self._keep_alive.ack() elif op == self.RESUMED: _log.info('Voice RESUME succeeded.') elif op == self.SESSION_DESCRIPTION: self._connection.mode = data['mode'] await self.load_secret_key(data) elif op == self.HELLO: interval = data['heartbeat_interval'] / 1000.0 self._keep_alive = VoiceKeepAliveHandler(ws=self, interval=min(interval, 5.0)) self._keep_alive.start() await self._hook(self, msg) async def initial_connection(self, data): state = self._connection state.ssrc = data['ssrc'] state.voice_port = data['port'] state.endpoint_ip = data['ip'] packet = bytearray(70) struct.pack_into('>H', packet, 0, 1) # 1 = Send struct.pack_into('>H', packet, 2, 70) # 70 = Length struct.pack_into('>I', packet, 4, state.ssrc) state.socket.sendto(packet, (state.endpoint_ip, state.voice_port)) recv = await self.loop.sock_recv(state.socket, 70) _log.debug('received packet in initial_connection: %s', recv) # the ip is ascii starting at the 4th byte and ending at the first null ip_start = 4 ip_end = recv.index(0, ip_start) state.ip = recv[ip_start:ip_end].decode('ascii') state.port = struct.unpack_from('>H', recv, len(recv) - 2)[0] _log.debug('detected ip: %s port: %s', state.ip, state.port) # there *should* always be at least one supported mode (xsalsa20_poly1305) modes = [mode for mode in data['modes'] if mode in self._connection.supported_modes] _log.debug('received supported encryption modes: %s', ", ".join(modes)) mode = modes[0] await self.select_protocol(state.ip, state.port, mode) _log.info('selected the voice protocol for use (%s)', mode) @property def latency(self): """:class:`float`: Latency between a HEARTBEAT and its HEARTBEAT_ACK in seconds.""" heartbeat = self._keep_alive return float('inf') if heartbeat is None else heartbeat.latency @property def average_latency(self): """:class:`list`: Average of last 20 HEARTBEAT latencies.""" heartbeat = self._keep_alive if heartbeat is None or not heartbeat.recent_ack_latencies: return float('inf') return sum(heartbeat.recent_ack_latencies) / len(heartbeat.recent_ack_latencies) async def load_secret_key(self, data): _log.info('received secret key for voice connection') self.secret_key = self._connection.secret_key = data.get('secret_key') await self.speak() await self.speak(False) async def poll_event(self): # This exception is handled up the chain msg = await asyncio.wait_for(self.ws.receive(), timeout=30.0) if msg.type is aiohttp.WSMsgType.TEXT: await self.received_message(utils._from_json(msg.data)) elif msg.type is aiohttp.WSMsgType.ERROR: _log.debug('Received %s', msg) raise ConnectionClosed(self.ws, shard_id=None) from msg.data elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSING): _log.debug('Received %s', msg) raise ConnectionClosed(self.ws, shard_id=None, code=self._close_code) async def close(self, code=1000): if self._keep_alive is not None: self._keep_alive.stop() self._close_code = code await self.ws.close(code=code)
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/gateway.py
gateway.py
import colorsys import random from typing import ( Any, Optional, Tuple, Type, TypeVar, Union, ) __all__ = ( 'Colour', 'Color', ) CT = TypeVar('CT', bound='Colour') class Colour: """Represents a Discord role colour. This class is similar to a (red, green, blue) :class:`tuple`. There is an alias for this called Color. .. container:: operations .. describe:: x == y Checks if two colours are equal. .. describe:: x != y Checks if two colours are not equal. .. describe:: hash(x) Return the colour's hash. .. describe:: str(x) Returns the hex format for the colour. .. describe:: int(x) Returns the raw colour value. Attributes ------------ value: :class:`int` The raw integer colour value. """ __slots__ = ('value',) def __init__(self, value: int): if not isinstance(value, int): raise TypeError(f'Expected int parameter, received {value.__class__.__name__} instead.') self.value: int = value def _get_byte(self, byte: int) -> int: return (self.value >> (8 * byte)) & 0xff def __eq__(self, other: Any) -> bool: return isinstance(other, Colour) and self.value == other.value def __ne__(self, other: Any) -> bool: return not self.__eq__(other) def __str__(self) -> str: return f'#{self.value:0>6x}' def __int__(self) -> int: return self.value def __repr__(self) -> str: return f'<Colour value={self.value}>' def __hash__(self) -> int: return hash(self.value) @property def r(self) -> int: """:class:`int`: Returns the red component of the colour.""" return self._get_byte(2) @property def g(self) -> int: """:class:`int`: Returns the green component of the colour.""" return self._get_byte(1) @property def b(self) -> int: """:class:`int`: Returns the blue component of the colour.""" return self._get_byte(0) def to_rgb(self) -> Tuple[int, int, int]: """Tuple[:class:`int`, :class:`int`, :class:`int`]: Returns an (r, g, b) tuple representing the colour.""" return (self.r, self.g, self.b) @classmethod def from_rgb(cls: Type[CT], r: int, g: int, b: int) -> CT: """Constructs a :class:`Colour` from an RGB tuple.""" return cls((r << 16) + (g << 8) + b) @classmethod def from_hsv(cls: Type[CT], h: float, s: float, v: float) -> CT: """Constructs a :class:`Colour` from an HSV tuple.""" rgb = colorsys.hsv_to_rgb(h, s, v) return cls.from_rgb(*(int(x * 255) for x in rgb)) @classmethod def default(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0``.""" return cls(0) @classmethod def random(cls: Type[CT], *, seed: Optional[Union[int, str, float, bytes, bytearray]] = None) -> CT: """A factory method that returns a :class:`Colour` with a random hue. .. note:: The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value. .. versionadded:: 1.6 Parameters ------------ seed: Optional[Union[:class:`int`, :class:`str`, :class:`float`, :class:`bytes`, :class:`bytearray`]] The seed to initialize the RNG with. If ``None`` is passed the default RNG is used. .. versionadded:: 1.7 """ rand = random if seed is None else random.Random(seed) return cls.from_hsv(rand.random(), 1, 1) @classmethod def teal(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x1abc9c``.""" return cls(0x1abc9c) @classmethod def dark_teal(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x11806a``.""" return cls(0x11806a) @classmethod def brand_green(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x57F287``. .. versionadded:: 2.0 """ return cls(0x57F287) @classmethod def green(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x2ecc71``.""" return cls(0x2ecc71) @classmethod def dark_green(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x1f8b4c``.""" return cls(0x1f8b4c) @classmethod def blue(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x3498db``.""" return cls(0x3498db) @classmethod def dark_blue(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x206694``.""" return cls(0x206694) @classmethod def purple(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x9b59b6``.""" return cls(0x9b59b6) @classmethod def dark_purple(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x71368a``.""" return cls(0x71368a) @classmethod def magenta(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xe91e63``.""" return cls(0xe91e63) @classmethod def dark_magenta(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xad1457``.""" return cls(0xad1457) @classmethod def gold(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xf1c40f``.""" return cls(0xf1c40f) @classmethod def dark_gold(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xc27c0e``.""" return cls(0xc27c0e) @classmethod def orange(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xe67e22``.""" return cls(0xe67e22) @classmethod def dark_orange(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xa84300``.""" return cls(0xa84300) @classmethod def brand_red(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xED4245``. .. versionadded:: 2.0 """ return cls(0xED4245) @classmethod def red(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xe74c3c``.""" return cls(0xe74c3c) @classmethod def dark_red(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x992d22``.""" return cls(0x992d22) @classmethod def lighter_grey(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x95a5a6``.""" return cls(0x95a5a6) lighter_gray = lighter_grey @classmethod def dark_grey(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x607d8b``.""" return cls(0x607d8b) dark_gray = dark_grey @classmethod def light_grey(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x979c9f``.""" return cls(0x979c9f) light_gray = light_grey @classmethod def darker_grey(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x546e7a``.""" return cls(0x546e7a) darker_gray = darker_grey @classmethod def og_blurple(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x7289da``.""" return cls(0x7289da) @classmethod def blurple(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x5865F2``.""" return cls(0x5865F2) @classmethod def greyple(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x99aab5``.""" return cls(0x99aab5) @classmethod def dark_theme(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x36393F``. This will appear transparent on Discord's dark theme. .. versionadded:: 1.5 """ return cls(0x36393F) @classmethod def fuchsia(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xEB459E``. .. versionadded:: 2.0 """ return cls(0xEB459E) @classmethod def yellow(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xFEE75C``. .. versionadded:: 2.0 """ return cls(0xFEE75C) Color = Colour
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/colour.py
colour.py
from __future__ import annotations from typing import Any, Callable, ClassVar, Dict, Iterator, List, Optional, Sequence, TYPE_CHECKING, Tuple from functools import partial from itertools import groupby import traceback import asyncio import sys import time import os from .item import Item, ItemCallbackType from ..components import ( Component, ActionRow as ActionRowComponent, _component_factory, Button as ButtonComponent, SelectMenu as SelectComponent, ) __all__ = ( 'View', ) if TYPE_CHECKING: from ..interactions import Interaction from ..message import Message from ..types.components import Component as ComponentPayload from ..state import ConnectionState def _walk_all_components(components: List[Component]) -> Iterator[Component]: for item in components: if isinstance(item, ActionRowComponent): yield from item.children else: yield item 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) return Item.from_component(component) class _ViewWeights: __slots__ = ( 'weights', ) def __init__(self, children: List[Item]): self.weights: List[int] = [0, 0, 0, 0, 0] key = lambda i: sys.maxsize if i.row is None else i.row children = sorted(children, key=key) for row, group in groupby(children, key=key): for item in group: self.add_item(item) def find_open_space(self, item: Item) -> int: for index, weight in enumerate(self.weights): if weight + item.width <= 5: return index raise ValueError('could not find open space for item') def add_item(self, item: Item) -> None: if item.row is not None: total = self.weights[item.row] + item.width if total > 5: raise ValueError(f'item would not fit at row {item.row} ({total} > 5 width)') self.weights[item.row] = total item._rendered_row = item.row else: index = self.find_open_space(item) self.weights[index] += item.width item._rendered_row = index def remove_item(self, item: Item) -> None: if item._rendered_row is not None: self.weights[item._rendered_row] -= item.width item._rendered_row = None def clear(self) -> None: self.weights = [0, 0, 0, 0, 0] class View: """Represents a UI view. This object must be inherited to create a UI within Discord. .. versionadded:: 2.0 Parameters ----------- timeout: Optional[:class:`float`] Timeout in seconds from last interaction with the UI before no longer accepting input. If ``None`` then there is no timeout. Attributes ------------ timeout: Optional[:class:`float`] Timeout from last interaction with the UI before no longer accepting input. If ``None`` then there is no timeout. children: List[:class:`Item`] The list of children attached to this view. """ __discord_ui_view__: ClassVar[bool] = True __view_children_items__: ClassVar[List[ItemCallbackType]] = [] def __init_subclass__(cls) -> None: children: List[ItemCallbackType] = [] for base in reversed(cls.__mro__): for member in base.__dict__.values(): if hasattr(member, '__discord_ui_model_type__'): children.append(member) if len(children) > 25: raise TypeError('View cannot have more than 25 children') cls.__view_children_items__ = children def __init__(self, *, timeout: Optional[float] = 180.0): self.timeout = timeout self.children: List[Item] = [] for func in self.__view_children_items__: item: Item = func.__discord_ui_model_type__(**func.__discord_ui_model_kwargs__) item.callback = partial(func, self, item) item._view = self setattr(self, func.__name__, item) self.children.append(item) self.__weights = _ViewWeights(self.children) loop = asyncio.get_running_loop() self.id: str = os.urandom(16).hex() self.__cancel_callback: Optional[Callable[[View], None]] = None self.__timeout_expiry: Optional[float] = None self.__timeout_task: Optional[asyncio.Task[None]] = None self.__stopped: asyncio.Future[bool] = loop.create_future() def __repr__(self) -> str: return f'<{self.__class__.__name__} timeout={self.timeout} children={len(self.children)}>' async def __timeout_task_impl(self) -> None: while True: # Guard just in case someone changes the value of the timeout at runtime if self.timeout is None: return if self.__timeout_expiry is None: return self._dispatch_timeout() # Check if we've elapsed our currently set timeout now = time.monotonic() if now >= self.__timeout_expiry: return self._dispatch_timeout() # Wait N seconds to see if timeout data has been refreshed await asyncio.sleep(self.__timeout_expiry - now) def to_components(self) -> List[Dict[str, Any]]: def key(item: Item) -> int: return item._rendered_row or 0 children = sorted(self.children, key=key) components: List[Dict[str, Any]] = [] for _, group in groupby(children, key=key): children = [item.to_component_dict() for item in group] if not children: continue components.append( { 'type': 1, 'components': children, } ) return components @classmethod def from_message(cls, message: Message, /, *, timeout: Optional[float] = 180.0) -> View: """Converts a message's components into a :class:`View`. The :attr:`.Message.components` of a message are read-only and separate types from those in the ``discord.ui`` namespace. In order to modify and edit message components they must be converted into a :class:`View` first. Parameters ----------- message: :class:`discord.Message` The message with components to convert into a view. timeout: Optional[:class:`float`] The timeout of the converted view. Returns -------- :class:`View` The converted view. This always returns a :class:`View` and not one of its subclasses. """ view = View(timeout=timeout) for component in _walk_all_components(message.components): view.add_item(_component_to_item(component)) return view @property def _expires_at(self) -> Optional[float]: if self.timeout: return time.monotonic() + self.timeout return None def add_item(self, item: Item) -> None: """Adds an item to the view. Parameters ----------- item: :class:`Item` The item to add to the view. Raises -------- TypeError An :class:`Item` was not passed. ValueError Maximum number of children has been exceeded (25) or the row the item is trying to be added to is full. """ if len(self.children) > 25: raise ValueError('maximum number of children exceeded') if not isinstance(item, Item): raise TypeError(f'expected Item not {item.__class__!r}') self.__weights.add_item(item) item._view = self self.children.append(item) def remove_item(self, item: Item) -> None: """Removes an item from the view. Parameters ----------- item: :class:`Item` The item to remove from the view. """ try: self.children.remove(item) except ValueError: pass else: self.__weights.remove_item(item) def clear_items(self) -> None: """Removes all items from the view.""" self.children.clear() self.__weights.clear() async def interaction_check(self, interaction: Interaction) -> bool: """|coro| A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction. This is useful to override if, for example, you want to ensure that the interaction author is a given user. The default implementation of this returns ``True``. .. note:: If an exception occurs within the body then the check is considered a failure and :meth:`on_error` is called. Parameters ----------- interaction: :class:`~discord.Interaction` The interaction that occurred. Returns --------- :class:`bool` Whether the view children's callbacks should be called. """ return True async def on_timeout(self) -> None: """|coro| A callback that is called when a view's timeout elapses without being explicitly stopped. """ pass async def on_error(self, error: Exception, item: Item, interaction: Interaction) -> None: """|coro| A callback that is called when an item's callback or :meth:`interaction_check` fails with an error. The default implementation prints the traceback to stderr. Parameters ----------- error: :class:`Exception` The exception that was raised. item: :class:`Item` The item that failed the dispatch. interaction: :class:`~discord.Interaction` The interaction that led to the failure. """ print(f'Ignoring exception in view {self} for item {item}:', file=sys.stderr) traceback.print_exception(error.__class__, error, error.__traceback__, file=sys.stderr) async def _scheduled_task(self, item: Item, interaction: Interaction): try: if self.timeout: self.__timeout_expiry = time.monotonic() + self.timeout allow = await self.interaction_check(interaction) if not allow: return await item.callback(interaction) if not interaction.response._responded: await interaction.response.defer() except Exception as e: return await self.on_error(e, item, interaction) def _start_listening_from_store(self, store: ViewStore) -> None: self.__cancel_callback = partial(store.remove_view) if self.timeout: loop = asyncio.get_running_loop() if self.__timeout_task is not None: self.__timeout_task.cancel() self.__timeout_expiry = time.monotonic() + self.timeout self.__timeout_task = loop.create_task(self.__timeout_task_impl()) def _dispatch_timeout(self): if self.__stopped.done(): return self.__stopped.set_result(True) asyncio.create_task(self.on_timeout(), name=f'discord-ui-view-timeout-{self.id}') def _dispatch_item(self, item: Item, interaction: Interaction): if self.__stopped.done(): return asyncio.create_task(self._scheduled_task(item, interaction), name=f'discord-ui-view-dispatch-{self.id}') def refresh(self, components: List[Component]): # This is pretty hacky at the moment # fmt: off old_state: Dict[Tuple[int, str], Item] = { (item.type.value, item.custom_id): item # type: ignore for item in self.children if item.is_dispatchable() } # fmt: on children: List[Item] = [] for component in _walk_all_components(components): try: older = old_state[(component.type.value, component.custom_id)] # type: ignore except (KeyError, AttributeError): children.append(_component_to_item(component)) else: older.refresh_component(component) children.append(older) self.children = children def stop(self) -> None: """Stops listening to interaction events from this view. This operation cannot be undone. """ if not self.__stopped.done(): self.__stopped.set_result(False) self.__timeout_expiry = None if self.__timeout_task is not None: self.__timeout_task.cancel() self.__timeout_task = None if self.__cancel_callback: self.__cancel_callback(self) self.__cancel_callback = None def is_finished(self) -> bool: """:class:`bool`: Whether the view has finished interacting.""" return self.__stopped.done() def is_dispatching(self) -> bool: """:class:`bool`: Whether the view has been added for dispatching purposes.""" return self.__cancel_callback is not None def is_persistent(self) -> bool: """:class:`bool`: Whether the view is set up as persistent. A persistent view has all their components with a set ``custom_id`` and a :attr:`timeout` set to ``None``. """ return self.timeout is None and all(item.is_persistent() for item in self.children) async def wait(self) -> bool: """Waits until the view has finished interacting. A view is considered finished when :meth:`stop` is called or it times out. Returns -------- :class:`bool` If ``True``, then the view timed out. If ``False`` then the view finished normally. """ return await self.__stopped class ViewStore: def __init__(self, state: ConnectionState): # (component_type, message_id, custom_id): (View, Item) self._views: Dict[Tuple[int, Optional[int], str], Tuple[View, Item]] = {} # message_id: View self._synced_message_views: Dict[int, View] = {} self._state: ConnectionState = state @property def persistent_views(self) -> Sequence[View]: # fmt: off views = { view.id: view for (_, (view, _)) in self._views.items() if view.is_persistent() } # fmt: on return list(views.values()) def __verify_integrity(self): to_remove: List[Tuple[int, Optional[int], str]] = [] for (k, (view, _)) in self._views.items(): if view.is_finished(): to_remove.append(k) for k in to_remove: del self._views[k] def add_view(self, view: View, message_id: Optional[int] = None): self.__verify_integrity() view._start_listening_from_store(self) for item in view.children: if item.is_dispatchable(): self._views[(item.type.value, message_id, item.custom_id)] = (view, item) # type: ignore if message_id is not None: self._synced_message_views[message_id] = view def remove_view(self, view: View): for item in view.children: if item.is_dispatchable(): self._views.pop((item.type.value, item.custom_id), None) # type: ignore for key, value in self._synced_message_views.items(): if value.id == view.id: del self._synced_message_views[key] break def dispatch(self, component_type: int, custom_id: str, interaction: Interaction): self.__verify_integrity() message_id: Optional[int] = interaction.message and interaction.message.id key = (component_type, message_id, custom_id) # Fallback to None message_id searches in case a persistent view # was added without an associated message_id value = self._views.get(key) or self._views.get((component_type, None, custom_id)) if value is None: return view, item = value item.refresh_state(interaction) view._dispatch_item(item, interaction) def is_message_tracked(self, message_id: int): return message_id in self._synced_message_views def remove_message_tracking(self, message_id: int) -> Optional[View]: return self._synced_message_views.pop(message_id, None) def update_from_message(self, message_id: int, components: List[ComponentPayload]): # pre-req: is_message_tracked == true view = self._synced_message_views[message_id] view.refresh([_component_factory(d) for d in components])
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ui/view.py
view.py
from __future__ import annotations from typing import Callable, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Union import inspect import os from .item import Item, ItemCallbackType from ..enums import ButtonStyle, ComponentType from ..partial_emoji import PartialEmoji, _EmojiTag from ..components import Button as ButtonComponent __all__ = ( 'Button', 'button', ) if TYPE_CHECKING: from .view import View from ..emoji import Emoji B = TypeVar('B', bound='Button') V = TypeVar('V', bound='View', covariant=True) class Button(Item[V]): """Represents a UI button. .. versionadded:: 2.0 Parameters ------------ style: :class:`discord.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[Union[:class:`.PartialEmoji`, :class:`.Emoji`, :class:`str`]] The emoji of the button, if available. row: Optional[:class:`int`] The relative row this button belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed). """ __item_repr_attributes__: Tuple[str, ...] = ( 'style', 'url', 'disabled', 'label', 'emoji', 'row', ) 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, ): super().__init__() if custom_id is not None and url is not None: raise TypeError('cannot mix both url and custom_id with Button') self._provided_custom_id = custom_id is not None if url is None and custom_id is None: custom_id = os.urandom(16).hex() if url is not None: style = ButtonStyle.link 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._underlying = ButtonComponent._raw_construct( type=ComponentType.button, custom_id=custom_id, url=url, disabled=disabled, label=label, style=style, emoji=emoji, ) self.row = row @property def style(self) -> ButtonStyle: """:class:`discord.ButtonStyle`: The style of the button.""" return self._underlying.style @style.setter def style(self, value: ButtonStyle): self._underlying.style = value @property def custom_id(self) -> Optional[str]: """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. """ return self._underlying.custom_id @custom_id.setter def custom_id(self, value: Optional[str]): if value is not None and not isinstance(value, str): raise TypeError('custom_id must be None or str') self._underlying.custom_id = value @property def url(self) -> Optional[str]: """Optional[:class:`str`]: The URL this button sends you to.""" return self._underlying.url @url.setter def url(self, value: Optional[str]): if value is not None and not isinstance(value, str): raise TypeError('url must be None or str') self._underlying.url = value @property def disabled(self) -> bool: """:class:`bool`: Whether the button is disabled or not.""" return self._underlying.disabled @disabled.setter def disabled(self, value: bool): self._underlying.disabled = bool(value) @property def label(self) -> Optional[str]: """Optional[:class:`str`]: The label of the button, if available.""" return self._underlying.label @label.setter def label(self, value: Optional[str]): self._underlying.label = str(value) if value is not None else value @property def emoji(self) -> Optional[PartialEmoji]: """Optional[:class:`.PartialEmoji`]: The emoji of the button, if available.""" return self._underlying.emoji @emoji.setter def emoji(self, value: Optional[Union[str, Emoji, PartialEmoji]]): # type: ignore if value is not None: if isinstance(value, str): self._underlying.emoji = PartialEmoji.from_str(value) elif isinstance(value, _EmojiTag): self._underlying.emoji = value._to_partial() else: raise TypeError(f'expected str, Emoji, or PartialEmoji, received {value.__class__} instead') else: self._underlying.emoji = None @classmethod def from_component(cls: Type[B], button: ButtonComponent) -> B: return cls( style=button.style, label=button.label, disabled=button.disabled, custom_id=button.custom_id, url=button.url, emoji=button.emoji, row=None, ) @property def type(self) -> ComponentType: return self._underlying.type def to_component_dict(self): return self._underlying.to_dict() def is_dispatchable(self) -> bool: return self.custom_id is not None def is_persistent(self) -> bool: if self.style is ButtonStyle.link: return self.url is not None return super().is_persistent() def refresh_component(self, button: ButtonComponent) -> None: self._underlying = button def button( *, label: Optional[str] = None, custom_id: Optional[str] = None, disabled: bool = False, style: ButtonStyle = ButtonStyle.secondary, emoji: Optional[Union[str, Emoji, PartialEmoji]] = None, row: Optional[int] = None, ) -> Callable[[ItemCallbackType], ItemCallbackType]: """A decorator that attaches a button to a component. The function being decorated should have three parameters, ``self`` representing the :class:`discord.ui.View`, the :class:`discord.ui.Button` being pressed and the :class:`discord.Interaction` you receive. .. note:: Buttons with a URL cannot be created with this function. Consider creating a :class:`Button` manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it. Parameters ------------ label: Optional[:class:`str`] The label of the button, if any. custom_id: Optional[:class:`str`] The ID of the button that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts. style: :class:`.ButtonStyle` The style of the button. Defaults to :attr:`.ButtonStyle.grey`. disabled: :class:`bool` Whether the button is disabled or not. Defaults to ``False``. emoji: Optional[Union[:class:`str`, :class:`.Emoji`, :class:`.PartialEmoji`]] The emoji of the button. This can be in string form or a :class:`.PartialEmoji` or a full :class:`.Emoji`. row: Optional[:class:`int`] The relative row this button belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed). """ def decorator(func: ItemCallbackType) -> ItemCallbackType: if not inspect.iscoroutinefunction(func): raise TypeError('button function must be a coroutine function') func.__discord_ui_model_type__ = Button func.__discord_ui_model_kwargs__ = { 'style': style, 'custom_id': custom_id, 'url': None, 'disabled': disabled, 'label': label, 'emoji': emoji, 'row': row, } return func return decorator
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ui/button.py
button.py
from __future__ import annotations from typing import List, Optional, TYPE_CHECKING, Tuple, TypeVar, Type, Callable, Union import inspect import os from .item import Item, ItemCallbackType from ..enums import ComponentType from ..partial_emoji import PartialEmoji from ..emoji import Emoji from ..interactions import Interaction from ..utils import MISSING from ..components import ( SelectOption, SelectMenu, ) __all__ = ( 'Select', 'select', ) if TYPE_CHECKING: from .view import View from ..types.components import SelectMenu as SelectMenuPayload from ..types.interactions import ( ComponentInteractionData, ) S = TypeVar('S', bound='Select') V = TypeVar('V', bound='View', covariant=True) class Select(Item[V]): """Represents a UI select menu. This is usually represented as a drop down menu. In order to get the selected items that the user has chosen, use :attr:`Select.values`. .. 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:`discord.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__() self._selected_values: List[str] = [] self._provided_custom_id = custom_id is not MISSING custom_id = os.urandom(16).hex() if custom_id is MISSING else custom_id options = [] if options is MISSING else options self._underlying = SelectMenu._raw_construct( custom_id=custom_id, type=ComponentType.select, placeholder=placeholder, min_values=min_values, max_values=max_values, options=options, disabled=disabled, ) self.row = row @property def custom_id(self) -> str: """:class:`str`: The ID of the select menu that gets received during an interaction.""" return self._underlying.custom_id @custom_id.setter def custom_id(self, value: str): if not isinstance(value, str): raise TypeError('custom_id must be None or str') self._underlying.custom_id = value @property def placeholder(self) -> Optional[str]: """Optional[:class:`str`]: The placeholder text that is shown if nothing is selected, if any.""" return self._underlying.placeholder @placeholder.setter def placeholder(self, value: Optional[str]): if value is not None and not isinstance(value, str): raise TypeError('placeholder must be None or str') self._underlying.placeholder = value @property def min_values(self) -> int: """:class:`int`: The minimum number of items that must be chosen for this select menu.""" return self._underlying.min_values @min_values.setter def min_values(self, value: int): self._underlying.min_values = int(value) @property def max_values(self) -> int: """:class:`int`: The maximum number of items that must be chosen for this select menu.""" return self._underlying.max_values @max_values.setter def max_values(self, value: int): self._underlying.max_values = int(value) @property def options(self) -> List[SelectOption]: """List[:class:`discord.SelectOption`]: A list of options that can be selected in this menu.""" return self._underlying.options @options.setter def options(self, value: List[SelectOption]): 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, ): """Adds an option to the select menu. To append a pre-existing :class:`discord.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): """Appends an option to the select menu. Parameters ----------- option: :class:`discord.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) @property def disabled(self) -> bool: """:class:`bool`: Whether the select is disabled or not.""" return self._underlying.disabled @disabled.setter def disabled(self, value: bool): self._underlying.disabled = bool(value) @property def values(self) -> List[str]: """List[:class:`str`]: A list of values that have been selected by the user.""" return self._selected_values @property def width(self) -> int: return 5 def to_component_dict(self) -> SelectMenuPayload: return self._underlying.to_dict() def refresh_component(self, component: SelectMenu) -> None: self._underlying = component def refresh_state(self, interaction: Interaction) -> None: data: ComponentInteractionData = interaction.data # type: ignore self._selected_values = data.get('values', []) @classmethod def from_component(cls: Type[S], component: SelectMenu) -> S: 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, ) @property def type(self) -> ComponentType: return self._underlying.type def is_dispatchable(self) -> bool: return True def 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], ItemCallbackType]: """A decorator that attaches a select menu to a component. The function being decorated should have three parameters, ``self`` representing the :class:`discord.ui.View`, the :class:`discord.ui.Select` being pressed and the :class:`discord.Interaction` you receive. In order to get the selected items that the user has chosen within the callback use :attr:`Select.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:`discord.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) -> ItemCallbackType: if not inspect.iscoroutinefunction(func): raise TypeError('select function must be a coroutine function') func.__discord_ui_model_type__ = Select 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
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ui/select.py
select.py
from __future__ import annotations from typing import Any, Callable, Coroutine, Dict, Generic, Optional, TYPE_CHECKING, Tuple, Type, TypeVar from ..interactions import Interaction __all__ = ( 'Item', ) if TYPE_CHECKING: from ..enums import ComponentType from .view import View from ..components import Component I = TypeVar('I', bound='Item') V = TypeVar('V', bound='View', covariant=True) ItemCallbackType = Callable[[Any, I, Interaction], Coroutine[Any, Any, Any]] class Item(Generic[V]): """Represents the base UI item that all UI components inherit from. The current UI items supported are: - :class:`discord.ui.Button` - :class:`discord.ui.Select` .. versionadded:: 2.0 """ __item_repr_attributes__: Tuple[str, ...] = ('row',) def __init__(self): self._view: Optional[V] = None self._row: Optional[int] = None self._rendered_row: Optional[int] = None # This works mostly well but there is a gotcha with # the interaction with from_component, since that technically provides # a custom_id most dispatchable items would get this set to True even though # it might not be provided by the library user. However, this edge case doesn't # actually affect the intended purpose of this check because from_component is # only called upon edit and we're mainly interested during initial creation time. self._provided_custom_id: bool = False def to_component_dict(self) -> Dict[str, Any]: raise NotImplementedError def refresh_component(self, component: Component) -> None: return None def refresh_state(self, interaction: Interaction) -> None: return None @classmethod def from_component(cls: Type[I], component: Component) -> I: return cls() @property def type(self) -> ComponentType: raise NotImplementedError def is_dispatchable(self) -> bool: return False def is_persistent(self) -> bool: return self._provided_custom_id def __repr__(self) -> str: attrs = ' '.join(f'{key}={getattr(self, key)!r}' for key in self.__item_repr_attributes__) return f'<{self.__class__.__name__} {attrs}>' @property def row(self) -> Optional[int]: return self._row @row.setter def row(self, value: Optional[int]): if value is None: self._row = None elif 5 > value >= 0: self._row = value else: raise ValueError('row cannot be negative or greater than or equal to 5') @property def width(self) -> int: return 1 @property def view(self) -> Optional[V]: """Optional[:class:`View`]: The underlying view for this item.""" return self._view async def callback(self, interaction: Interaction): """|coro| The callback associated with this UI item. This can be overriden by subclasses. Parameters ----------- interaction: :class:`.Interaction` The interaction that triggered this UI item. """ pass
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ui/item.py
item.py
from __future__ import annotations import threading import logging import json import time import re from urllib.parse import quote as urlquote from typing import Any, Dict, List, Literal, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Union, overload from .. import utils from ..errors import InvalidArgument, HTTPException, Forbidden, NotFound, DiscordServerError from ..message import Message from ..http import Route from ..channel import PartialMessageable from .async_ import BaseWebhook, handle_message_parameters, _WebhookState __all__ = ( 'SyncWebhook', 'SyncWebhookMessage', ) _log = logging.getLogger(__name__) if TYPE_CHECKING: from ..file import File from ..embeds import Embed from ..mentions import AllowedMentions from ..types.webhook import ( Webhook as WebhookPayload, ) from ..abc import Snowflake try: from requests import Session, Response except ModuleNotFoundError: pass MISSING = utils.MISSING class DeferredLock: def __init__(self, lock: threading.Lock): self.lock = lock self.delta: Optional[float] = None def __enter__(self): self.lock.acquire() return self def delay_by(self, delta: float) -> None: self.delta = delta def __exit__(self, type, value, traceback): if self.delta: time.sleep(self.delta) self.lock.release() class WebhookAdapter: def __init__(self): self._locks: Dict[Any, threading.Lock] = {} 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: headers: Dict[str, str] = {} 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) elif response.status_code == 404: raise NotFound(response, data) else: 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) class _WebhookContext(threading.local): adapter: Optional[WebhookAdapter] = None _context = _WebhookContext() def _get_webhook_adapter() -> WebhookAdapter: if _context.adapter is None: _context.adapter = WebhookAdapter() return _context.adapter class SyncWebhookMessage(Message): """Represents a message sent from your webhook. This allows you to edit or delete a message sent by your webhook. This inherits from :class:`discord.Message` with changes to :meth:`edit` and :meth:`delete` to work. .. versionadded:: 2.0 """ _state: _WebhookState def edit( self, content: Optional[str] = MISSING, embeds: List[Embed] = MISSING, embed: Optional[Embed] = MISSING, file: File = MISSING, files: List[File] = MISSING, allowed_mentions: Optional[AllowedMentions] = None, ) -> SyncWebhookMessage: """Edits the message. 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. allowed_mentions: :class:`AllowedMentions` Controls the mentions being processed in this message. See :meth:`.abc.Messageable.send` for more information. Raises ------- HTTPException Editing the message failed. Forbidden Edited a message that is not yours. TypeError You specified both ``embed`` and ``embeds`` or ``file`` and ``files`` ValueError The length of ``embeds`` was invalid InvalidArgument There was no token associated with this webhook. Returns -------- :class:`SyncWebhookMessage` The newly edited message. """ return self._state._webhook.edit_message( self.id, content=content, embeds=embeds, embed=embed, file=file, files=files, allowed_mentions=allowed_mentions, ) def delete(self, *, delay: Optional[float] = None) -> None: """Deletes the message. Parameters ----------- delay: Optional[:class:`float`] If provided, the number of seconds to wait before deleting the message. This blocks the thread. Raises ------ Forbidden You do not have proper permissions to delete the message. NotFound The message was deleted already. HTTPException Deleting the message failed. """ if delay is not None: time.sleep(delay) self._state._webhook.delete_message(self.id) class SyncWebhook(BaseWebhook): """Represents a synchronous Discord webhook. For an asynchronous counterpart, see :class:`Webhook`. .. container:: operations .. describe:: x == y Checks if two webhooks are equal. .. describe:: x != y Checks if two webhooks are not equal. .. describe:: hash(x) Returns the webhooks's hash. .. versionchanged:: 1.4 Webhooks are now comparable and hashable. Attributes ------------ id: :class:`int` The webhook's ID type: :class:`WebhookType` The type of the webhook. .. versionadded:: 1.3 token: Optional[:class:`str`] The authentication token of the webhook. If this is ``None`` then the webhook cannot be used to make requests. guild_id: Optional[:class:`int`] The guild ID this webhook is for. channel_id: Optional[:class:`int`] The channel ID this webhook is for. user: Optional[:class:`abc.User`] The user this webhook was created by. If the webhook was received without authentication then this will be ``None``. name: Optional[:class:`str`] The default name of the webhook. source_guild: Optional[:class:`PartialWebhookGuild`] The guild of the channel that this webhook is following. Only given if :attr:`type` is :attr:`WebhookType.channel_follower`. .. versionadded:: 2.0 source_channel: Optional[:class:`PartialWebhookChannel`] The channel that this webhook is following. Only given if :attr:`type` is :attr:`WebhookType.channel_follower`. .. versionadded:: 2.0 """ __slots__: Tuple[str, ...] = ('session',) def __init__(self, data: WebhookPayload, session: Session, token: Optional[str] = None, state=None): super().__init__(data, token, state) self.session = session def __repr__(self): return f'<Webhook id={self.id!r}>' @property def url(self) -> str: """:class:`str` : Returns the webhook's url.""" return f'https://discord.com/api/webhooks/{self.id}/{self.token}' @classmethod def partial(cls, id: int, token: str, *, session: Session = MISSING, bot_token: Optional[str] = None) -> SyncWebhook: """Creates a partial :class:`Webhook`. Parameters ----------- id: :class:`int` The ID of the webhook. token: :class:`str` The authentication token of the webhook. session: :class:`requests.Session` The session to use to send requests with. Note that the library does not manage the session and will not close it. If not given, the ``requests`` auto session creation functions are used instead. bot_token: Optional[:class:`str`] The bot authentication token for authenticated requests involving the webhook. Returns -------- :class:`Webhook` A partial :class:`Webhook`. A partial webhook is just a webhook object with an ID and a token. """ data: WebhookPayload = { 'id': id, 'type': 1, 'token': token, } import requests if session is not MISSING: if not isinstance(session, requests.Session): raise TypeError(f'expected requests.Session not {session.__class__!r}') else: session = requests # type: ignore return cls(data, session, token=bot_token) @classmethod def from_url(cls, url: str, *, session: Session = MISSING, bot_token: Optional[str] = None) -> SyncWebhook: """Creates a partial :class:`Webhook` from a webhook URL. Parameters ------------ url: :class:`str` The URL of the webhook. session: :class:`requests.Session` The session to use to send requests with. Note that the library does not manage the session and will not close it. If not given, the ``requests`` auto session creation functions are used instead. bot_token: Optional[:class:`str`] The bot authentication token for authenticated requests involving the webhook. Raises ------- InvalidArgument The URL is invalid. Returns -------- :class:`Webhook` A partial :class:`Webhook`. A partial webhook is just a webhook object with an ID and a token. """ m = re.search(r'discord(?:app)?.com/api/webhooks/(?P<id>[0-9]{17,20})/(?P<token>[A-Za-z0-9\.\-\_]{60,68})', url) if m is None: raise InvalidArgument('Invalid webhook URL given.') data: Dict[str, Any] = m.groupdict() data['type'] = 1 import requests if session is not MISSING: if not isinstance(session, requests.Session): raise TypeError(f'expected requests.Session not {session.__class__!r}') else: session = requests # type: ignore return cls(data, session, token=bot_token) # type: ignore def fetch(self, *, prefer_auth: bool = True) -> SyncWebhook: """Fetches the current webhook. This could be used to get a full webhook from a partial webhook. .. note:: When fetching with an unauthenticated webhook, i.e. :meth:`is_authenticated` returns ``False``, then the returned webhook does not contain any user information. Parameters ----------- prefer_auth: :class:`bool` Whether to use the bot token over the webhook token if available. Defaults to ``True``. Raises ------- HTTPException Could not fetch the webhook NotFound Could not find the webhook by this ID InvalidArgument This webhook does not have a token associated with it. Returns -------- :class:`SyncWebhook` The fetched webhook. """ adapter: WebhookAdapter = _get_webhook_adapter() if prefer_auth and self.auth_token: data = adapter.fetch_webhook(self.id, self.auth_token, session=self.session) elif self.token: data = adapter.fetch_webhook_with_token(self.id, self.token, session=self.session) else: raise InvalidArgument('This webhook does not have a token associated with it') return SyncWebhook(data, self.session, token=self.auth_token, state=self._state) def delete(self, *, reason: Optional[str] = None, prefer_auth: bool = True) -> None: """Deletes this Webhook. Parameters ------------ reason: Optional[:class:`str`] The reason for deleting this webhook. Shows up on the audit log. .. versionadded:: 1.4 prefer_auth: :class:`bool` Whether to use the bot token over the webhook token if available. Defaults to ``True``. Raises ------- HTTPException Deleting the webhook failed. NotFound This webhook does not exist. Forbidden You do not have permissions to delete this webhook. InvalidArgument This webhook does not have a token associated with it. """ if self.token is None and self.auth_token is None: raise InvalidArgument('This webhook does not have a token associated with it') adapter: WebhookAdapter = _get_webhook_adapter() if prefer_auth and self.auth_token: adapter.delete_webhook(self.id, token=self.auth_token, session=self.session, reason=reason) elif self.token: adapter.delete_webhook_with_token(self.id, self.token, session=self.session, reason=reason) def edit( self, *, reason: Optional[str] = None, name: Optional[str] = MISSING, avatar: Optional[bytes] = MISSING, channel: Optional[Snowflake] = None, prefer_auth: bool = True, ) -> SyncWebhook: """Edits this Webhook. Parameters ------------ name: Optional[:class:`str`] The webhook's new default name. avatar: Optional[:class:`bytes`] A :term:`py:bytes-like object` representing the webhook's new default avatar. channel: Optional[:class:`abc.Snowflake`] The webhook's new channel. This requires an authenticated webhook. reason: Optional[:class:`str`] The reason for editing this webhook. Shows up on the audit log. .. versionadded:: 1.4 prefer_auth: :class:`bool` Whether to use the bot token over the webhook token if available. Defaults to ``True``. Raises ------- HTTPException Editing the webhook failed. NotFound This webhook does not exist. InvalidArgument This webhook does not have a token associated with it or it tried editing a channel without authentication. Returns -------- :class:`SyncWebhook` The newly edited webhook. """ if self.token is None and self.auth_token is None: raise InvalidArgument('This webhook does not have a token associated with it') payload = {} if name is not MISSING: payload['name'] = str(name) if name is not None else None if avatar is not MISSING: payload['avatar'] = utils._bytes_to_base64_data(avatar) if avatar is not None else None adapter: WebhookAdapter = _get_webhook_adapter() data: Optional[WebhookPayload] = None # If a channel is given, always use the authenticated endpoint if channel is not None: if self.auth_token is None: raise InvalidArgument('Editing channel requires authenticated webhook') payload['channel_id'] = channel.id data = adapter.edit_webhook(self.id, self.auth_token, payload=payload, session=self.session, reason=reason) if prefer_auth and self.auth_token: data = adapter.edit_webhook(self.id, self.auth_token, payload=payload, session=self.session, reason=reason) elif self.token: data = adapter.edit_webhook_with_token(self.id, self.token, payload=payload, session=self.session, reason=reason) if data is None: raise RuntimeError('Unreachable code hit: data was not assigned') return SyncWebhook(data=data, session=self.session, token=self.auth_token, state=self._state) def _create_message(self, data): state = _WebhookState(self, parent=self._state) # state may be artificial (unlikely at this point...) channel = self.channel or PartialMessageable(state=self._state, id=int(data['channel_id'])) # type: ignore # state is artificial return SyncWebhookMessage(data=data, state=state, channel=channel) # type: ignore @overload def send( self, content: str = MISSING, *, username: str = MISSING, avatar_url: Any = MISSING, tts: bool = MISSING, file: File = MISSING, files: List[File] = MISSING, embed: Embed = MISSING, embeds: List[Embed] = MISSING, allowed_mentions: AllowedMentions = MISSING, wait: Literal[True], ) -> SyncWebhookMessage: ... @overload def send( self, content: str = MISSING, *, username: str = MISSING, avatar_url: Any = MISSING, tts: bool = MISSING, file: File = MISSING, files: List[File] = MISSING, embed: Embed = MISSING, embeds: List[Embed] = MISSING, allowed_mentions: AllowedMentions = MISSING, wait: Literal[False] = ..., ) -> None: ... def send( self, content: str = MISSING, *, username: str = MISSING, avatar_url: Any = MISSING, tts: bool = False, file: File = MISSING, files: List[File] = MISSING, embed: Embed = MISSING, embeds: List[Embed] = MISSING, allowed_mentions: AllowedMentions = MISSING, thread: Snowflake = MISSING, wait: bool = False, ) -> Optional[SyncWebhookMessage]: """Sends a message using the webhook. The content must be a type that can convert to a string through ``str(content)``. To upload a single file, the ``file`` parameter should be used with a single :class:`File` object. If the ``embed`` parameter is provided, it must be of type :class:`Embed` and it must be a rich embed type. You cannot mix the ``embed`` parameter with the ``embeds`` parameter, which must be a :class:`list` of :class:`Embed` objects to send. Parameters ------------ content: :class:`str` The content of the message to send. wait: :class:`bool` Whether the server should wait before sending a response. This essentially means that the return type of this function changes from ``None`` to a :class:`WebhookMessage` if set to ``True``. username: :class:`str` The username to send with this message. If no username is provided then the default username for the webhook is used. avatar_url: :class:`str` The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used. If this is not a string then it is explicitly cast using ``str``. tts: :class:`bool` Indicates if the message should be sent using text-to-speech. 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. embed: :class:`Embed` The rich embed for the content to send. This cannot be mixed with ``embeds`` parameter. embeds: List[:class:`Embed`] A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the ``embed`` parameter. allowed_mentions: :class:`AllowedMentions` Controls the mentions being processed in this message. .. versionadded:: 1.4 thread: :class:`~discord.abc.Snowflake` The thread to send this message to. .. versionadded:: 2.0 Raises -------- HTTPException Sending the message failed. NotFound This webhook was not found. Forbidden The authorization token for the webhook is incorrect. TypeError You specified both ``embed`` and ``embeds`` or ``file`` and ``files`` ValueError The length of ``embeds`` was invalid InvalidArgument There was no token associated with this webhook. Returns --------- Optional[:class:`SyncWebhookMessage`] If ``wait`` is ``True`` then the message that was sent, otherwise ``None``. """ if self.token is None: raise InvalidArgument('This webhook does not have a token associated with it') previous_mentions: Optional[AllowedMentions] = getattr(self._state, 'allowed_mentions', None) if content is None: content = MISSING params = handle_message_parameters( content=content, username=username, avatar_url=avatar_url, tts=tts, file=file, files=files, embed=embed, embeds=embeds, allowed_mentions=allowed_mentions, previous_allowed_mentions=previous_mentions, ) adapter: WebhookAdapter = _get_webhook_adapter() thread_id: Optional[int] = None if thread is not MISSING: thread_id = thread.id data = adapter.execute_webhook( self.id, self.token, session=self.session, payload=params.payload, multipart=params.multipart, files=params.files, thread_id=thread_id, wait=wait, ) if wait: return self._create_message(data) def fetch_message(self, id: int, /) -> SyncWebhookMessage: """Retrieves a single :class:`~discord.SyncWebhookMessage` owned by this webhook. .. versionadded:: 2.0 Parameters ------------ id: :class:`int` The message ID to look for. Raises -------- ~discord.NotFound The specified message was not found. ~discord.Forbidden You do not have the permissions required to get a message. ~discord.HTTPException Retrieving the message failed. InvalidArgument There was no token associated with this webhook. Returns -------- :class:`~discord.SyncWebhookMessage` The message asked for. """ if self.token is None: raise InvalidArgument('This webhook does not have a token associated with it') adapter: WebhookAdapter = _get_webhook_adapter() data = adapter.get_webhook_message( self.id, self.token, id, session=self.session, ) return self._create_message(data) def edit_message( self, message_id: int, *, content: Optional[str] = MISSING, embeds: List[Embed] = MISSING, embed: Optional[Embed] = MISSING, file: File = MISSING, files: List[File] = MISSING, allowed_mentions: Optional[AllowedMentions] = None, ) -> SyncWebhookMessage: """Edits a message owned by this webhook. This is a lower level interface to :meth:`WebhookMessage.edit` in case you only have an ID. .. versionadded:: 1.6 Parameters ------------ message_id: :class:`int` The message ID to edit. 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. allowed_mentions: :class:`AllowedMentions` Controls the mentions being processed in this message. See :meth:`.abc.Messageable.send` for more information. Raises ------- HTTPException Editing the message failed. Forbidden Edited a message that is not yours. TypeError You specified both ``embed`` and ``embeds`` or ``file`` and ``files`` ValueError The length of ``embeds`` was invalid InvalidArgument There was no token associated with this webhook. """ if self.token is None: raise InvalidArgument('This webhook does not have a token associated with it') previous_mentions: Optional[AllowedMentions] = getattr(self._state, 'allowed_mentions', None) params = handle_message_parameters( content=content, file=file, files=files, embed=embed, embeds=embeds, allowed_mentions=allowed_mentions, previous_allowed_mentions=previous_mentions, ) adapter: WebhookAdapter = _get_webhook_adapter() data = adapter.edit_webhook_message( self.id, self.token, message_id, session=self.session, payload=params.payload, multipart=params.multipart, files=params.files, ) return self._create_message(data) def delete_message(self, message_id: int, /) -> None: """Deletes a message owned by this webhook. This is a lower level interface to :meth:`WebhookMessage.delete` in case you only have an ID. .. versionadded:: 1.6 Parameters ------------ message_id: :class:`int` The message ID to delete. Raises ------- HTTPException Deleting the message failed. Forbidden Deleted a message that is not yours. """ if self.token is None: raise InvalidArgument('This webhook does not have a token associated with it') adapter: WebhookAdapter = _get_webhook_adapter() adapter.delete_webhook_message( self.id, self.token, message_id, session=self.session, )
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/webhook/sync.py
sync.py
from __future__ import annotations import logging import asyncio import json import re from urllib.parse import quote as urlquote from typing import Any, Dict, List, Literal, NamedTuple, Optional, TYPE_CHECKING, Tuple, Union, overload from contextvars import ContextVar import aiohttp from .. import utils from ..errors import InvalidArgument, HTTPException, Forbidden, NotFound, DiscordServerError from ..message import Message from ..enums import try_enum, WebhookType from ..user import BaseUser, User from ..asset import Asset from ..http import Route from ..mixins import Hashable from ..channel import PartialMessageable __all__ = ( 'Webhook', 'WebhookMessage', 'PartialWebhookChannel', 'PartialWebhookGuild', ) _log = logging.getLogger(__name__) if TYPE_CHECKING: from ..file import File from ..embeds import Embed from ..mentions import AllowedMentions from ..state import ConnectionState from ..http import Response from ..types.webhook import ( Webhook as WebhookPayload, ) from ..types.message import ( Message as MessagePayload, ) from ..guild import Guild from ..channel import TextChannel from ..abc import Snowflake from ..ui.view import View import datetime MISSING = utils.MISSING class AsyncDeferredLock: def __init__(self, lock: asyncio.Lock): self.lock = lock self.delta: Optional[float] = None async def __aenter__(self): await self.lock.acquire() return self def delay_by(self, delta: float) -> None: self.delta = delta async def __aexit__(self, type, value, traceback): if self.delta: await asyncio.sleep(self.delta) self.lock.release() class AsyncWebhookAdapter: def __init__(self): self._locks: Dict[Any, asyncio.Lock] = {} async def request( self, route: Route, session: aiohttp.ClientSession, *, 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: headers: Dict[str, str] = {} files = files or [] to_send: Optional[Union[str, aiohttp.FormData]] = None bucket = (route.webhook_id, route.webhook_token) try: lock = self._locks[bucket] except KeyError: self._locks[bucket] = lock = asyncio.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[aiohttp.ClientResponse] = None data: Optional[Union[Dict[str, Any], str]] = None method = route.method url = route.url webhook_id = route.webhook_id async with AsyncDeferredLock(lock) as lock: for attempt in range(5): for file in files: file.reset(seek=attempt) if multipart: form_data = aiohttp.FormData() for p in multipart: form_data.add_field(**p) to_send = form_data try: async with session.request(method, url, data=to_send, 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, ) data = (await response.text(encoding='utf-8')) 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 != 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 >= 200: return data if response.status == 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) await asyncio.sleep(retry_after) continue if response.status >= 500: await asyncio.sleep(1 + attempt * 2) continue if response.status == 403: raise Forbidden(response, data) elif response.status == 404: raise NotFound(response, data) else: raise HTTPException(response, data) except OSError as e: if attempt < 4 and e.errno in (54, 10054): await asyncio.sleep(1 + attempt * 2) continue raise if response: if response.status >= 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: aiohttp.ClientSession, reason: Optional[str] = None, ) -> Response[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: aiohttp.ClientSession, reason: Optional[str] = None, ) -> Response[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: aiohttp.ClientSession, reason: Optional[str] = None, ) -> Response[WebhookPayload]: 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: aiohttp.ClientSession, reason: Optional[str] = None, ) -> Response[WebhookPayload]: 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: aiohttp.ClientSession, 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, ) -> Response[Optional[MessagePayload]]: 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: aiohttp.ClientSession, ) -> Response[MessagePayload]: 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: aiohttp.ClientSession, payload: Optional[Dict[str, Any]] = None, multipart: Optional[List[Dict[str, Any]]] = None, files: Optional[List[File]] = None, ) -> Response[Message]: 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: aiohttp.ClientSession, ) -> Response[None]: 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: aiohttp.ClientSession, ) -> Response[WebhookPayload]: 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: aiohttp.ClientSession, ) -> Response[WebhookPayload]: route = Route('GET', '/webhooks/{webhook_id}/{webhook_token}', webhook_id=webhook_id, webhook_token=token) return self.request(route, session=session) def create_interaction_response( self, interaction_id: int, token: str, *, session: aiohttp.ClientSession, type: int, data: Optional[Dict[str, Any]] = None, ) -> Response[None]: payload: Dict[str, Any] = { 'type': type, } if data is not None: payload['data'] = data route = Route( 'POST', '/interactions/{webhook_id}/{webhook_token}/callback', webhook_id=interaction_id, webhook_token=token, ) return self.request(route, session=session, payload=payload) def get_original_interaction_response( self, application_id: int, token: str, *, session: aiohttp.ClientSession, ) -> Response[MessagePayload]: r = Route( 'GET', '/webhooks/{webhook_id}/{webhook_token}/messages/@original', webhook_id=application_id, webhook_token=token, ) return self.request(r, session=session) def edit_original_interaction_response( self, application_id: int, token: str, *, session: aiohttp.ClientSession, payload: Optional[Dict[str, Any]] = None, multipart: Optional[List[Dict[str, Any]]] = None, files: Optional[List[File]] = None, ) -> Response[MessagePayload]: r = Route( 'PATCH', '/webhooks/{webhook_id}/{webhook_token}/messages/@original', webhook_id=application_id, webhook_token=token, ) return self.request(r, session, payload=payload, multipart=multipart, files=files) def delete_original_interaction_response( self, application_id: int, token: str, *, session: aiohttp.ClientSession, ) -> Response[None]: r = Route( 'DELETE', '/webhooks/{webhook_id}/{wehook_token}/messages/@original', webhook_id=application_id, wehook_token=token, ) return self.request(r, session=session) class ExecuteWebhookParameters(NamedTuple): payload: Optional[Dict[str, Any]] multipart: Optional[List[Dict[str, Any]]] files: Optional[List[File]] def handle_message_parameters( content: Optional[str] = MISSING, *, username: str = MISSING, avatar_url: Any = MISSING, tts: bool = False, ephemeral: bool = False, file: File = MISSING, files: List[File] = MISSING, embed: Optional[Embed] = MISSING, embeds: List[Embed] = MISSING, view: Optional[View] = MISSING, allowed_mentions: Optional[AllowedMentions] = MISSING, previous_allowed_mentions: Optional[AllowedMentions] = None, ) -> ExecuteWebhookParameters: if files is not MISSING and file is not MISSING: raise TypeError('Cannot mix file and files keyword arguments.') if embeds is not MISSING and embed is not MISSING: raise TypeError('Cannot mix embed and embeds keyword arguments.') payload = {} if embeds is not MISSING: if len(embeds) > 10: raise InvalidArgument('embeds has a maximum of 10 elements.') 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 ephemeral: payload['flags'] = 64 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', 'value': utils._to_json(payload)}) payload = None if len(files) == 1: file = files[0] multipart.append( { 'name': 'file', 'value': file.fp, 'filename': file.filename, 'content_type': 'application/octet-stream', } ) else: for index, file in enumerate(files): multipart.append( { 'name': f'file{index}', 'value': file.fp, 'filename': file.filename, 'content_type': 'application/octet-stream', } ) return ExecuteWebhookParameters(payload=payload, multipart=multipart, files=files) async_context: ContextVar[AsyncWebhookAdapter] = ContextVar('async_webhook_context', default=AsyncWebhookAdapter()) class PartialWebhookChannel(Hashable): """Represents a partial channel for webhooks. These are typically given for channel follower webhooks. .. versionadded:: 2.0 Attributes ----------- id: :class:`int` The partial channel's ID. name: :class:`str` The partial channel's name. """ __slots__ = ('id', 'name') def __init__(self, *, data): self.id = int(data['id']) self.name = data['name'] def __repr__(self): return f'<PartialWebhookChannel name={self.name!r} id={self.id}>' class PartialWebhookGuild(Hashable): """Represents a partial guild for webhooks. These are typically given for channel follower webhooks. .. versionadded:: 2.0 Attributes ----------- id: :class:`int` The partial guild's ID. name: :class:`str` The partial guild's name. """ __slots__ = ('id', 'name', '_icon', '_state') def __init__(self, *, data, state): self._state = state self.id = int(data['id']) self.name = data['name'] self._icon = data['icon'] def __repr__(self): return f'<PartialWebhookGuild name={self.name!r} id={self.id}>' @property 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) class _FriendlyHttpAttributeErrorHelper: __slots__ = () def __getattr__(self, attr): raise AttributeError('PartialWebhookState does not support http methods.') class _WebhookState: __slots__ = ('_parent', '_webhook') def __init__(self, webhook: Any, parent: Optional[Union[ConnectionState, _WebhookState]]): self._webhook: Any = webhook self._parent: Optional[ConnectionState] if isinstance(parent, _WebhookState): self._parent = None else: self._parent = parent def _get_guild(self, guild_id): if self._parent is not None: return self._parent._get_guild(guild_id) return None def store_user(self, data): if self._parent is not None: return self._parent.store_user(data) # state parameter is artificial return BaseUser(state=self, data=data) # type: ignore def create_user(self, data): # state parameter is artificial return BaseUser(state=self, data=data) # type: ignore @property def http(self): if self._parent is not None: return self._parent.http # Some data classes assign state.http and that should be kosher # however, using it should result in a late-binding error. return _FriendlyHttpAttributeErrorHelper() def __getattr__(self, attr): if self._parent is not None: return getattr(self._parent, attr) raise AttributeError(f'PartialWebhookState does not support {attr!r}.') class WebhookMessage(Message): """Represents a message sent from your webhook. This allows you to edit or delete a message sent by your webhook. This inherits from :class:`discord.Message` with changes to :meth:`edit` and :meth:`delete` to work. .. versionadded:: 1.6 """ _state: _WebhookState async def edit( self, content: Optional[str] = MISSING, embeds: List[Embed] = MISSING, embed: Optional[Embed] = MISSING, file: File = MISSING, files: List[File] = MISSING, view: Optional[View] = MISSING, allowed_mentions: Optional[AllowedMentions] = None, ) -> WebhookMessage: """|coro| Edits the message. .. versionadded:: 1.6 .. versionchanged:: 2.0 The edit is no longer in-place, instead the newly edited message is returned. 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. .. versionadded:: 2.0 files: List[:class:`File`] A list of files to send with the content. This cannot be mixed with the ``file`` parameter. .. versionadded:: 2.0 allowed_mentions: :class:`AllowedMentions` Controls the mentions being processed in this message. See :meth:`.abc.Messageable.send` for more information. view: Optional[:class:`~discord.ui.View`] The updated view to update this message with. If ``None`` is passed then the view is removed. .. versionadded:: 2.0 Raises ------- HTTPException Editing the message failed. Forbidden Edited a message that is not yours. TypeError You specified both ``embed`` and ``embeds`` or ``file`` and ``files`` ValueError The length of ``embeds`` was invalid InvalidArgument There was no token associated with this webhook. Returns -------- :class:`WebhookMessage` The newly edited message. """ return await self._state._webhook.edit_message( self.id, content=content, embeds=embeds, embed=embed, file=file, files=files, view=view, allowed_mentions=allowed_mentions, ) async def delete(self, *, delay: Optional[float] = None) -> None: """|coro| Deletes the message. 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 ------ 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 inner_call(delay: float = delay): await asyncio.sleep(delay) try: await self._state._webhook.delete_message(self.id) except HTTPException: pass asyncio.create_task(inner_call()) else: await self._state._webhook.delete_message(self.id) class BaseWebhook(Hashable): __slots__: Tuple[str, ...] = ( 'id', 'type', 'guild_id', 'channel_id', 'token', 'auth_token', 'user', 'name', '_avatar', 'source_channel', 'source_guild', '_state', ) def __init__(self, data: WebhookPayload, token: Optional[str] = None, state: Optional[ConnectionState] = None): self.auth_token: Optional[str] = token self._state: Union[ConnectionState, _WebhookState] = state or _WebhookState(self, parent=state) self._update(data) def _update(self, data: WebhookPayload): self.id = int(data['id']) self.type = try_enum(WebhookType, int(data['type'])) self.channel_id = utils._get_as_snowflake(data, 'channel_id') self.guild_id = utils._get_as_snowflake(data, 'guild_id') self.name = data.get('name') self._avatar = data.get('avatar') self.token = data.get('token') user = data.get('user') self.user: Optional[Union[BaseUser, User]] = None if user is not None: # state parameter may be _WebhookState self.user = User(state=self._state, data=user) # type: ignore source_channel = data.get('source_channel') if source_channel: source_channel = PartialWebhookChannel(data=source_channel) self.source_channel: Optional[PartialWebhookChannel] = source_channel source_guild = data.get('source_guild') if source_guild: source_guild = PartialWebhookGuild(data=source_guild, state=self._state) self.source_guild: Optional[PartialWebhookGuild] = source_guild def is_partial(self) -> bool: """:class:`bool`: Whether the webhook is a "partial" webhook. .. versionadded:: 2.0""" return self.channel_id is None def is_authenticated(self) -> bool: """:class:`bool`: Whether the webhook is authenticated with a bot token. .. versionadded:: 2.0 """ return self.auth_token is not None @property def guild(self) -> Optional[Guild]: """Optional[:class:`Guild`]: The guild this webhook belongs to. If this is a partial webhook, then this will always return ``None``. """ return self._state and self._state._get_guild(self.guild_id) @property def channel(self) -> Optional[TextChannel]: """Optional[:class:`TextChannel`]: The text channel this webhook belongs to. If this is a partial webhook, then this will always return ``None``. """ guild = self.guild return guild and guild.get_channel(self.channel_id) # type: ignore @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the webhook's creation time in UTC.""" return utils.snowflake_time(self.id) @property def avatar(self) -> Asset: """:class:`Asset`: Returns an :class:`Asset` for the avatar the webhook has. If the webhook does not have a traditional avatar, an asset for the default avatar is returned instead. """ if self._avatar is None: # Default is always blurple apparently return Asset._from_default_avatar(self._state, 0) return Asset._from_avatar(self._state, self.id, self._avatar) class Webhook(BaseWebhook): """Represents an asynchronous Discord webhook. Webhooks are a form to send messages to channels in Discord without a bot user or authentication. There are two main ways to use Webhooks. The first is through the ones received by the library such as :meth:`.Guild.webhooks` and :meth:`.TextChannel.webhooks`. The ones received by the library will automatically be bound using the library's internal HTTP session. The second form involves creating a webhook object manually using the :meth:`~.Webhook.from_url` or :meth:`~.Webhook.partial` classmethods. For example, creating a webhook from a URL and using :doc:`aiohttp <aio:index>`: .. code-block:: python3 from discord import Webhook import aiohttp async def foo(): async with aiohttp.ClientSession() as session: webhook = Webhook.from_url('url-here', session=session) await webhook.send('Hello World', username='Foo') For a synchronous counterpart, see :class:`SyncWebhook`. .. container:: operations .. describe:: x == y Checks if two webhooks are equal. .. describe:: x != y Checks if two webhooks are not equal. .. describe:: hash(x) Returns the webhooks's hash. .. versionchanged:: 1.4 Webhooks are now comparable and hashable. Attributes ------------ id: :class:`int` The webhook's ID type: :class:`WebhookType` The type of the webhook. .. versionadded:: 1.3 token: Optional[:class:`str`] The authentication token of the webhook. If this is ``None`` then the webhook cannot be used to make requests. guild_id: Optional[:class:`int`] The guild ID this webhook is for. channel_id: Optional[:class:`int`] The channel ID this webhook is for. user: Optional[:class:`abc.User`] The user this webhook was created by. If the webhook was received without authentication then this will be ``None``. name: Optional[:class:`str`] The default name of the webhook. source_guild: Optional[:class:`PartialWebhookGuild`] The guild of the channel that this webhook is following. Only given if :attr:`type` is :attr:`WebhookType.channel_follower`. .. versionadded:: 2.0 source_channel: Optional[:class:`PartialWebhookChannel`] The channel that this webhook is following. Only given if :attr:`type` is :attr:`WebhookType.channel_follower`. .. versionadded:: 2.0 """ __slots__: Tuple[str, ...] = ('session',) def __init__(self, data: WebhookPayload, session: aiohttp.ClientSession, token: Optional[str] = None, state=None): super().__init__(data, token, state) self.session = session def __repr__(self): return f'<Webhook id={self.id!r}>' @property def url(self) -> str: """:class:`str` : Returns the webhook's url.""" return f'https://discord.com/api/webhooks/{self.id}/{self.token}' @classmethod def partial(cls, id: int, token: str, *, session: aiohttp.ClientSession, bot_token: Optional[str] = None) -> Webhook: """Creates a partial :class:`Webhook`. Parameters ----------- id: :class:`int` The ID of the webhook. token: :class:`str` The authentication token of the webhook. session: :class:`aiohttp.ClientSession` The session to use to send requests with. Note that the library does not manage the session and will not close it. .. versionadded:: 2.0 bot_token: Optional[:class:`str`] The bot authentication token for authenticated requests involving the webhook. .. versionadded:: 2.0 Returns -------- :class:`Webhook` A partial :class:`Webhook`. A partial webhook is just a webhook object with an ID and a token. """ data: WebhookPayload = { 'id': id, 'type': 1, 'token': token, } return cls(data, session, token=bot_token) @classmethod def from_url(cls, url: str, *, session: aiohttp.ClientSession, bot_token: Optional[str] = None) -> Webhook: """Creates a partial :class:`Webhook` from a webhook URL. Parameters ------------ url: :class:`str` The URL of the webhook. session: :class:`aiohttp.ClientSession` The session to use to send requests with. Note that the library does not manage the session and will not close it. .. versionadded:: 2.0 bot_token: Optional[:class:`str`] The bot authentication token for authenticated requests involving the webhook. .. versionadded:: 2.0 Raises ------- InvalidArgument The URL is invalid. Returns -------- :class:`Webhook` A partial :class:`Webhook`. A partial webhook is just a webhook object with an ID and a token. """ m = re.search(r'discord(?:app)?.com/api/webhooks/(?P<id>[0-9]{17,20})/(?P<token>[A-Za-z0-9\.\-\_]{60,68})', url) if m is None: raise InvalidArgument('Invalid webhook URL given.') data: Dict[str, Any] = m.groupdict() data['type'] = 1 return cls(data, session, token=bot_token) # type: ignore @classmethod def _as_follower(cls, data, *, channel, user) -> Webhook: name = f"{channel.guild} #{channel}" feed: WebhookPayload = { 'id': data['webhook_id'], 'type': 2, 'name': name, 'channel_id': channel.id, 'guild_id': channel.guild.id, 'user': {'username': user.name, 'discriminator': user.discriminator, 'id': user.id, 'avatar': user._avatar}, } state = channel._state session = channel._state.http._HTTPClient__session return cls(feed, session=session, state=state, token=state.http.token) @classmethod def from_state(cls, data, state) -> Webhook: session = state.http._HTTPClient__session return cls(data, session=session, state=state, token=state.http.token) async def fetch(self, *, prefer_auth: bool = True) -> Webhook: """|coro| Fetches the current webhook. This could be used to get a full webhook from a partial webhook. .. versionadded:: 2.0 .. note:: When fetching with an unauthenticated webhook, i.e. :meth:`is_authenticated` returns ``False``, then the returned webhook does not contain any user information. Parameters ----------- prefer_auth: :class:`bool` Whether to use the bot token over the webhook token if available. Defaults to ``True``. Raises ------- HTTPException Could not fetch the webhook NotFound Could not find the webhook by this ID InvalidArgument This webhook does not have a token associated with it. Returns -------- :class:`Webhook` The fetched webhook. """ adapter = async_context.get() if prefer_auth and self.auth_token: data = await adapter.fetch_webhook(self.id, self.auth_token, session=self.session) elif self.token: data = await adapter.fetch_webhook_with_token(self.id, self.token, session=self.session) else: raise InvalidArgument('This webhook does not have a token associated with it') return Webhook(data, self.session, token=self.auth_token, state=self._state) async def delete(self, *, reason: Optional[str] = None, prefer_auth: bool = True): """|coro| Deletes this Webhook. Parameters ------------ reason: Optional[:class:`str`] The reason for deleting this webhook. Shows up on the audit log. .. versionadded:: 1.4 prefer_auth: :class:`bool` Whether to use the bot token over the webhook token if available. Defaults to ``True``. .. versionadded:: 2.0 Raises ------- HTTPException Deleting the webhook failed. NotFound This webhook does not exist. Forbidden You do not have permissions to delete this webhook. InvalidArgument This webhook does not have a token associated with it. """ if self.token is None and self.auth_token is None: raise InvalidArgument('This webhook does not have a token associated with it') adapter = async_context.get() if prefer_auth and self.auth_token: await adapter.delete_webhook(self.id, token=self.auth_token, session=self.session, reason=reason) elif self.token: await adapter.delete_webhook_with_token(self.id, self.token, session=self.session, reason=reason) async def edit( self, *, reason: Optional[str] = None, name: Optional[str] = MISSING, avatar: Optional[bytes] = MISSING, channel: Optional[Snowflake] = None, prefer_auth: bool = True, ) -> Webhook: """|coro| Edits this Webhook. Parameters ------------ name: Optional[:class:`str`] The webhook's new default name. avatar: Optional[:class:`bytes`] A :term:`py:bytes-like object` representing the webhook's new default avatar. channel: Optional[:class:`abc.Snowflake`] The webhook's new channel. This requires an authenticated webhook. .. versionadded:: 2.0 reason: Optional[:class:`str`] The reason for editing this webhook. Shows up on the audit log. .. versionadded:: 1.4 prefer_auth: :class:`bool` Whether to use the bot token over the webhook token if available. Defaults to ``True``. .. versionadded:: 2.0 Raises ------- HTTPException Editing the webhook failed. NotFound This webhook does not exist. InvalidArgument This webhook does not have a token associated with it or it tried editing a channel without authentication. """ if self.token is None and self.auth_token is None: raise InvalidArgument('This webhook does not have a token associated with it') payload = {} if name is not MISSING: payload['name'] = str(name) if name is not None else None if avatar is not MISSING: payload['avatar'] = utils._bytes_to_base64_data(avatar) if avatar is not None else None adapter = async_context.get() data: Optional[WebhookPayload] = None # If a channel is given, always use the authenticated endpoint if channel is not None: if self.auth_token is None: raise InvalidArgument('Editing channel requires authenticated webhook') payload['channel_id'] = channel.id data = await adapter.edit_webhook(self.id, self.auth_token, payload=payload, session=self.session, reason=reason) if prefer_auth and self.auth_token: data = await adapter.edit_webhook(self.id, self.auth_token, payload=payload, session=self.session, reason=reason) elif self.token: data = await adapter.edit_webhook_with_token( self.id, self.token, payload=payload, session=self.session, reason=reason ) if data is None: raise RuntimeError('Unreachable code hit: data was not assigned') return Webhook(data=data, session=self.session, token=self.auth_token, state=self._state) def _create_message(self, data): state = _WebhookState(self, parent=self._state) # state may be artificial (unlikely at this point...) channel = self.channel or PartialMessageable(state=self._state, id=int(data['channel_id'])) # type: ignore # state is artificial return WebhookMessage(data=data, state=state, channel=channel) # type: ignore @overload async def send( self, content: str = MISSING, *, username: str = MISSING, avatar_url: Any = MISSING, tts: bool = MISSING, ephemeral: bool = MISSING, file: File = MISSING, files: List[File] = MISSING, embed: Embed = MISSING, embeds: List[Embed] = MISSING, allowed_mentions: AllowedMentions = MISSING, view: View = MISSING, thread: Snowflake = MISSING, wait: Literal[True], ) -> WebhookMessage: ... @overload async def send( self, content: str = MISSING, *, username: str = MISSING, avatar_url: Any = MISSING, tts: bool = MISSING, ephemeral: bool = MISSING, file: File = MISSING, files: List[File] = MISSING, embed: Embed = MISSING, embeds: List[Embed] = MISSING, allowed_mentions: AllowedMentions = MISSING, view: View = MISSING, thread: Snowflake = MISSING, wait: Literal[False] = ..., ) -> None: ... async def send( self, content: str = MISSING, *, username: str = MISSING, avatar_url: Any = MISSING, tts: bool = False, ephemeral: bool = False, file: File = MISSING, files: List[File] = MISSING, embed: Embed = MISSING, embeds: List[Embed] = MISSING, allowed_mentions: AllowedMentions = MISSING, view: View = MISSING, thread: Snowflake = MISSING, wait: bool = False, ) -> Optional[WebhookMessage]: """|coro| Sends a message using the webhook. The content must be a type that can convert to a string through ``str(content)``. To upload a single file, the ``file`` parameter should be used with a single :class:`File` object. If the ``embed`` parameter is provided, it must be of type :class:`Embed` and it must be a rich embed type. You cannot mix the ``embed`` parameter with the ``embeds`` parameter, which must be a :class:`list` of :class:`Embed` objects to send. Parameters ------------ content: :class:`str` The content of the message to send. wait: :class:`bool` Whether the server should wait before sending a response. This essentially means that the return type of this function changes from ``None`` to a :class:`WebhookMessage` if set to ``True``. If the type of webhook is :attr:`WebhookType.application` then this is always set to ``True``. username: :class:`str` The username to send with this message. If no username is provided then the default username for the webhook is used. avatar_url: :class:`str` The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used. If this is not a string then it is explicitly cast using ``str``. tts: :class:`bool` Indicates if the message should be sent using text-to-speech. ephemeral: :class:`bool` Indicates if the message should only be visible to the user. This is only available to :attr:`WebhookType.application` webhooks. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes. .. versionadded:: 2.0 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. embed: :class:`Embed` The rich embed for the content to send. This cannot be mixed with ``embeds`` parameter. embeds: List[:class:`Embed`] A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the ``embed`` parameter. allowed_mentions: :class:`AllowedMentions` Controls the mentions being processed in this message. .. versionadded:: 1.4 view: :class:`discord.ui.View` The view to send with the message. You can only send a view if this webhook is not partial and has state attached. A webhook has state attached if the webhook is managed by the library. .. versionadded:: 2.0 thread: :class:`~discord.abc.Snowflake` The thread to send this webhook to. .. versionadded:: 2.0 Raises -------- HTTPException Sending the message failed. NotFound This webhook was not found. Forbidden The authorization token for the webhook is incorrect. TypeError You specified both ``embed`` and ``embeds`` or ``file`` and ``files``. ValueError The length of ``embeds`` was invalid. InvalidArgument There was no token associated with this webhook or ``ephemeral`` was passed with the improper webhook type or there was no state attached with this webhook when giving it a view. Returns --------- Optional[:class:`WebhookMessage`] If ``wait`` is ``True`` then the message that was sent, otherwise ``None``. """ if self.token is None: raise InvalidArgument('This webhook does not have a token associated with it') previous_mentions: Optional[AllowedMentions] = getattr(self._state, 'allowed_mentions', None) if content is None: content = MISSING application_webhook = self.type is WebhookType.application if ephemeral and not application_webhook: raise InvalidArgument('ephemeral messages can only be sent from application webhooks') if application_webhook: wait = True if view is not MISSING: if isinstance(self._state, _WebhookState): raise InvalidArgument('Webhook views require an associated state with the webhook') if ephemeral is True and view.timeout is None: view.timeout = 15 * 60.0 params = handle_message_parameters( content=content, username=username, avatar_url=avatar_url, tts=tts, file=file, files=files, embed=embed, embeds=embeds, ephemeral=ephemeral, view=view, allowed_mentions=allowed_mentions, previous_allowed_mentions=previous_mentions, ) adapter = async_context.get() thread_id: Optional[int] = None if thread is not MISSING: thread_id = thread.id data = await adapter.execute_webhook( self.id, self.token, session=self.session, payload=params.payload, multipart=params.multipart, files=params.files, thread_id=thread_id, wait=wait, ) msg = None if wait: msg = self._create_message(data) if view is not MISSING and not view.is_finished(): message_id = None if msg is None else msg.id self._state.store_view(view, message_id) return msg async def fetch_message(self, id: int) -> WebhookMessage: """|coro| Retrieves a single :class:`~discord.WebhookMessage` owned by this webhook. .. versionadded:: 2.0 Parameters ------------ id: :class:`int` The message ID to look for. Raises -------- ~discord.NotFound The specified message was not found. ~discord.Forbidden You do not have the permissions required to get a message. ~discord.HTTPException Retrieving the message failed. InvalidArgument There was no token associated with this webhook. Returns -------- :class:`~discord.WebhookMessage` The message asked for. """ if self.token is None: raise InvalidArgument('This webhook does not have a token associated with it') adapter = async_context.get() data = await adapter.get_webhook_message( self.id, self.token, id, session=self.session, ) return self._create_message(data) async def edit_message( self, message_id: int, *, content: Optional[str] = MISSING, embeds: List[Embed] = MISSING, embed: Optional[Embed] = MISSING, file: File = MISSING, files: List[File] = MISSING, view: Optional[View] = MISSING, allowed_mentions: Optional[AllowedMentions] = None, ) -> WebhookMessage: """|coro| Edits a message owned by this webhook. This is a lower level interface to :meth:`WebhookMessage.edit` in case you only have an ID. .. versionadded:: 1.6 .. versionchanged:: 2.0 The edit is no longer in-place, instead the newly edited message is returned. Parameters ------------ message_id: :class:`int` The message ID to edit. 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. .. versionadded:: 2.0 files: List[:class:`File`] A list of files to send with the content. This cannot be mixed with the ``file`` parameter. .. versionadded:: 2.0 allowed_mentions: :class:`AllowedMentions` Controls the mentions being processed in this message. See :meth:`.abc.Messageable.send` for more information. view: Optional[:class:`~discord.ui.View`] The updated view to update this message with. If ``None`` is passed then the view is removed. The webhook must have state attached, similar to :meth:`send`. .. versionadded:: 2.0 Raises ------- HTTPException Editing the message failed. Forbidden Edited a message that is not yours. TypeError You specified both ``embed`` and ``embeds`` or ``file`` and ``files`` ValueError The length of ``embeds`` was invalid InvalidArgument There was no token associated with this webhook or the webhook had no state. Returns -------- :class:`WebhookMessage` The newly edited webhook message. """ if self.token is None: raise InvalidArgument('This webhook does not have a token associated with it') if view is not MISSING: if isinstance(self._state, _WebhookState): raise InvalidArgument('This webhook does not have state associated with it') self._state.prevent_view_updates_for(message_id) previous_mentions: Optional[AllowedMentions] = getattr(self._state, 'allowed_mentions', None) params = handle_message_parameters( content=content, file=file, files=files, embed=embed, embeds=embeds, view=view, allowed_mentions=allowed_mentions, previous_allowed_mentions=previous_mentions, ) adapter = async_context.get() data = await adapter.edit_webhook_message( self.id, self.token, message_id, session=self.session, payload=params.payload, multipart=params.multipart, files=params.files, ) message = self._create_message(data) if view and not view.is_finished(): self._state.store_view(view, message_id) return message async def delete_message(self, message_id: int, /) -> None: """|coro| Deletes a message owned by this webhook. This is a lower level interface to :meth:`WebhookMessage.delete` in case you only have an ID. .. versionadded:: 1.6 Parameters ------------ message_id: :class:`int` The message ID to delete. Raises ------- HTTPException Deleting the message failed. Forbidden Deleted a message that is not yours. """ if self.token is None: raise InvalidArgument('This webhook does not have a token associated with it') adapter = async_context.get() await adapter.delete_webhook_message( self.id, self.token, message_id, session=self.session, )
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/webhook/async_.py
async_.py
from __future__ import annotations from typing import List, Literal, Optional, TypedDict, Union from .snowflake import Snowflake, SnowflakeList from .member import Member, UserWithMember from .user import User from .emoji import PartialEmoji from .embed import Embed from .channel import ChannelType from .components import Component from .interactions import MessageInteraction from .sticker import StickerItem class ChannelMention(TypedDict): id: Snowflake guild_id: Snowflake type: ChannelType name: str class Reaction(TypedDict): count: int me: bool emoji: PartialEmoji class _AttachmentOptional(TypedDict, total=False): height: Optional[int] width: Optional[int] content_type: str spoiler: bool class Attachment(_AttachmentOptional): id: Snowflake filename: str size: int url: str proxy_url: str MessageActivityType = Literal[1, 2, 3, 5] class MessageActivity(TypedDict): type: MessageActivityType party_id: str class _MessageApplicationOptional(TypedDict, total=False): cover_image: str class MessageApplication(_MessageApplicationOptional): id: Snowflake description: str icon: Optional[str] name: str class MessageReference(TypedDict, total=False): message_id: Snowflake channel_id: Snowflake guild_id: Snowflake fail_if_not_exists: bool class _MessageOptional(TypedDict, total=False): guild_id: Snowflake member: Member mention_channels: List[ChannelMention] reactions: List[Reaction] nonce: Union[int, str] webhook_id: Snowflake activity: MessageActivity application: MessageApplication application_id: Snowflake message_reference: MessageReference flags: int sticker_items: List[StickerItem] referenced_message: Optional[Message] interaction: MessageInteraction components: List[Component] MessageType = Literal[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 18, 19, 20, 21] class Message(_MessageOptional): id: Snowflake channel_id: Snowflake author: User content: str timestamp: str edited_timestamp: Optional[str] tts: bool mention_everyone: bool mentions: List[UserWithMember] mention_roles: SnowflakeList attachments: List[Attachment] embeds: List[Embed] pinned: bool type: MessageType AllowedMentionType = Literal['roles', 'users', 'everyone'] class AllowedMentions(TypedDict): parse: List[AllowedMentionType] roles: SnowflakeList users: SnowflakeList replied_user: bool
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/types/message.py
message.py
from typing import List, Literal, Optional, TypedDict, Union from .user import PartialUser from .snowflake import Snowflake from .threads import ThreadMetadata, ThreadMember, ThreadArchiveDuration OverwriteType = Literal[0, 1] class PermissionOverwrite(TypedDict): id: Snowflake type: OverwriteType allow: str deny: str ChannelType = Literal[0, 1, 2, 3, 4, 5, 6, 10, 11, 12, 13] class _BaseChannel(TypedDict): id: Snowflake name: str class _BaseGuildChannel(_BaseChannel): guild_id: Snowflake position: int permission_overwrites: List[PermissionOverwrite] nsfw: bool parent_id: Optional[Snowflake] class PartialChannel(_BaseChannel): type: ChannelType class _TextChannelOptional(TypedDict, total=False): topic: str last_message_id: Optional[Snowflake] last_pin_timestamp: str rate_limit_per_user: int default_auto_archive_duration: ThreadArchiveDuration class TextChannel(_BaseGuildChannel, _TextChannelOptional): type: Literal[0] class NewsChannel(_BaseGuildChannel, _TextChannelOptional): type: Literal[5] VideoQualityMode = Literal[1, 2] class _VoiceChannelOptional(TypedDict, total=False): rtc_region: Optional[str] video_quality_mode: VideoQualityMode class VoiceChannel(_BaseGuildChannel, _VoiceChannelOptional): type: Literal[2] bitrate: int user_limit: int class CategoryChannel(_BaseGuildChannel): type: Literal[4] class StoreChannel(_BaseGuildChannel): type: Literal[6] class _StageChannelOptional(TypedDict, total=False): rtc_region: Optional[str] topic: str class StageChannel(_BaseGuildChannel, _StageChannelOptional): type: Literal[13] bitrate: int user_limit: int class _ThreadChannelOptional(TypedDict, total=False): member: ThreadMember owner_id: Snowflake rate_limit_per_user: int last_message_id: Optional[Snowflake] last_pin_timestamp: str class ThreadChannel(_BaseChannel, _ThreadChannelOptional): type: Literal[10, 11, 12] guild_id: Snowflake parent_id: Snowflake owner_id: Snowflake nsfw: bool last_message_id: Optional[Snowflake] rate_limit_per_user: int message_count: int member_count: int thread_metadata: ThreadMetadata GuildChannel = Union[TextChannel, NewsChannel, VoiceChannel, CategoryChannel, StoreChannel, StageChannel, ThreadChannel] class DMChannel(_BaseChannel): type: Literal[1] last_message_id: Optional[Snowflake] recipients: List[PartialUser] class GroupDMChannel(_BaseChannel): type: Literal[3] icon: Optional[str] owner_id: Snowflake Channel = Union[GuildChannel, DMChannel, GroupDMChannel] PrivacyLevel = Literal[1, 2] class StageInstance(TypedDict): id: Snowflake guild_id: Snowflake channel_id: Snowflake topic: str privacy_level: PrivacyLevel discoverable_disabled: bool
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/types/channel.py
channel.py
from typing import List, Literal, Optional, TypedDict from .snowflake import Snowflake from .channel import GuildChannel from .voice import GuildVoiceState from .welcome_screen import WelcomeScreen from .activity import PartialPresenceUpdate from .role import Role from .member import Member from .emoji import Emoji from .user import User from .threads import Thread class Ban(TypedDict): reason: Optional[str] user: User class _UnavailableGuildOptional(TypedDict, total=False): unavailable: bool class UnavailableGuild(_UnavailableGuildOptional): id: Snowflake class _GuildOptional(TypedDict, total=False): icon_hash: Optional[str] owner: bool permissions: str widget_enabled: bool widget_channel_id: Optional[Snowflake] joined_at: Optional[str] large: bool member_count: int voice_states: List[GuildVoiceState] members: List[Member] channels: List[GuildChannel] presences: List[PartialPresenceUpdate] threads: List[Thread] max_presences: Optional[int] max_members: int premium_subscription_count: int max_video_channel_users: int DefaultMessageNotificationLevel = Literal[0, 1] ExplicitContentFilterLevel = Literal[0, 1, 2] MFALevel = Literal[0, 1] VerificationLevel = Literal[0, 1, 2, 3, 4] NSFWLevel = Literal[0, 1, 2, 3] PremiumTier = Literal[0, 1, 2, 3] GuildFeature = Literal[ 'ANIMATED_ICON', 'BANNER', 'COMMERCE', 'COMMUNITY', 'DISCOVERABLE', 'FEATURABLE', 'INVITE_SPLASH', 'MEMBER_VERIFICATION_GATE_ENABLED', 'MONETIZATION_ENABLED', 'MORE_EMOJI', 'MORE_STICKERS', 'NEWS', 'PARTNERED', 'PREVIEW_ENABLED', 'PRIVATE_THREADS', 'SEVEN_DAY_THREAD_ARCHIVE', 'THREE_DAY_THREAD_ARCHIVE', 'TICKETED_EVENTS_ENABLED', 'VANITY_URL', 'VERIFIED', 'VIP_REGIONS', 'WELCOME_SCREEN_ENABLED', ] class _BaseGuildPreview(UnavailableGuild): name: str icon: Optional[str] splash: Optional[str] discovery_splash: Optional[str] emojis: List[Emoji] features: List[GuildFeature] description: Optional[str] class _GuildPreviewUnique(TypedDict): approximate_member_count: int approximate_presence_count: int class GuildPreview(_BaseGuildPreview, _GuildPreviewUnique): ... class Guild(_BaseGuildPreview, _GuildOptional): owner_id: Snowflake region: str afk_channel_id: Optional[Snowflake] afk_timeout: int verification_level: VerificationLevel default_message_notifications: DefaultMessageNotificationLevel explicit_content_filter: ExplicitContentFilterLevel roles: List[Role] mfa_level: MFALevel nsfw_level: NSFWLevel application_id: Optional[Snowflake] system_channel_id: Optional[Snowflake] system_channel_flags: int rules_channel_id: Optional[Snowflake] vanity_url_code: Optional[str] banner: Optional[str] premium_tier: PremiumTier preferred_locale: str public_updates_channel_id: Optional[Snowflake] class InviteGuild(Guild, total=False): welcome_screen: WelcomeScreen class GuildWithCounts(Guild, _GuildPreviewUnique): ... class GuildPrune(TypedDict): pruned: Optional[int] class ChannelPositionUpdate(TypedDict): id: Snowflake position: Optional[int] lock_permissions: Optional[bool] parent_id: Optional[Snowflake] class _RolePositionRequired(TypedDict): id: Snowflake class RolePositionUpdate(_RolePositionRequired, total=False): position: Optional[Snowflake]
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/types/guild.py
guild.py
from __future__ import annotations from typing import List, Literal, Optional, TypedDict, Union from .webhook import Webhook from .guild import MFALevel, VerificationLevel, ExplicitContentFilterLevel, DefaultMessageNotificationLevel from .integration import IntegrationExpireBehavior, PartialIntegration from .user import User from .snowflake import Snowflake from .role import Role from .channel import ChannelType, VideoQualityMode, PermissionOverwrite from .threads import Thread AuditLogEvent = Literal[ 1, 10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 31, 32, 40, 41, 42, 50, 51, 52, 60, 61, 62, 72, 73, 74, 75, 80, 81, 82, 83, 84, 85, 90, 91, 92, 110, 111, 112, ] class _AuditLogChange_Str(TypedDict): key: Literal[ 'name', 'description', 'preferred_locale', 'vanity_url_code', 'topic', 'code', 'allow', 'deny', 'permissions', 'tags' ] new_value: str old_value: str class _AuditLogChange_AssetHash(TypedDict): key: Literal['icon_hash', 'splash_hash', 'discovery_splash_hash', 'banner_hash', 'avatar_hash', 'asset'] new_value: str old_value: str class _AuditLogChange_Snowflake(TypedDict): key: Literal[ 'id', 'owner_id', 'afk_channel_id', 'rules_channel_id', 'public_updates_channel_id', 'widget_channel_id', 'system_channel_id', 'application_id', 'channel_id', 'inviter_id', 'guild_id', ] new_value: Snowflake old_value: Snowflake class _AuditLogChange_Bool(TypedDict): key: Literal[ 'widget_enabled', 'nsfw', 'hoist', 'mentionable', 'temporary', 'deaf', 'mute', 'nick', 'enabled_emoticons', 'region', 'rtc_region', 'available', 'archived', 'locked', ] new_value: bool old_value: bool class _AuditLogChange_Int(TypedDict): key: Literal[ 'afk_timeout', 'prune_delete_days', 'position', 'bitrate', 'rate_limit_per_user', 'color', 'max_uses', 'max_age', 'user_limit', 'auto_archive_duration', 'default_auto_archive_duration', ] new_value: int old_value: int class _AuditLogChange_ListRole(TypedDict): key: Literal['$add', '$remove'] new_value: List[Role] old_value: List[Role] class _AuditLogChange_MFALevel(TypedDict): key: Literal['mfa_level'] new_value: MFALevel old_value: MFALevel class _AuditLogChange_VerificationLevel(TypedDict): key: Literal['verification_level'] new_value: VerificationLevel old_value: VerificationLevel class _AuditLogChange_ExplicitContentFilter(TypedDict): key: Literal['explicit_content_filter'] new_value: ExplicitContentFilterLevel old_value: ExplicitContentFilterLevel class _AuditLogChange_DefaultMessageNotificationLevel(TypedDict): key: Literal['default_message_notifications'] new_value: DefaultMessageNotificationLevel old_value: DefaultMessageNotificationLevel class _AuditLogChange_ChannelType(TypedDict): key: Literal['type'] new_value: ChannelType old_value: ChannelType class _AuditLogChange_IntegrationExpireBehaviour(TypedDict): key: Literal['expire_behavior'] new_value: IntegrationExpireBehavior old_value: IntegrationExpireBehavior class _AuditLogChange_VideoQualityMode(TypedDict): key: Literal['video_quality_mode'] new_value: VideoQualityMode old_value: VideoQualityMode class _AuditLogChange_Overwrites(TypedDict): key: Literal['permission_overwrites'] new_value: List[PermissionOverwrite] old_value: List[PermissionOverwrite] AuditLogChange = Union[ _AuditLogChange_Str, _AuditLogChange_AssetHash, _AuditLogChange_Snowflake, _AuditLogChange_Int, _AuditLogChange_Bool, _AuditLogChange_ListRole, _AuditLogChange_MFALevel, _AuditLogChange_VerificationLevel, _AuditLogChange_ExplicitContentFilter, _AuditLogChange_DefaultMessageNotificationLevel, _AuditLogChange_ChannelType, _AuditLogChange_IntegrationExpireBehaviour, _AuditLogChange_VideoQualityMode, _AuditLogChange_Overwrites, ] class AuditEntryInfo(TypedDict): delete_member_days: str members_removed: str channel_id: Snowflake message_id: Snowflake count: str id: Snowflake type: Literal['0', '1'] role_name: str class _AuditLogEntryOptional(TypedDict, total=False): changes: List[AuditLogChange] options: AuditEntryInfo reason: str class AuditLogEntry(_AuditLogEntryOptional): target_id: Optional[str] user_id: Optional[Snowflake] id: Snowflake action_type: AuditLogEvent class AuditLog(TypedDict): webhooks: List[Webhook] users: List[User] audit_log_entries: List[AuditLogEntry] integrations: List[PartialIntegration] threads: List[Thread]
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/types/audit_log.py
audit_log.py
from __future__ import annotations from typing import Optional, TYPE_CHECKING, Dict, TypedDict, Union, List, Literal from .snowflake import Snowflake from .components import Component, ComponentType from .embed import Embed from .channel import ChannelType from .member import Member from .role import Role from .user import User if TYPE_CHECKING: from .message import AllowedMentions, Message ApplicationCommandType = Literal[1, 2, 3] class _ApplicationCommandOptional(TypedDict, total=False): options: List[ApplicationCommandOption] type: ApplicationCommandType class ApplicationCommand(_ApplicationCommandOptional): id: Snowflake application_id: Snowflake name: str description: str class _ApplicationCommandOptionOptional(TypedDict, total=False): choices: List[ApplicationCommandOptionChoice] options: List[ApplicationCommandOption] ApplicationCommandOptionType = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] class ApplicationCommandOption(_ApplicationCommandOptionOptional): type: ApplicationCommandOptionType name: str description: str required: bool class ApplicationCommandOptionChoice(TypedDict): name: str value: Union[str, int] ApplicationCommandPermissionType = Literal[1, 2] class ApplicationCommandPermissions(TypedDict): id: Snowflake type: ApplicationCommandPermissionType permission: bool class BaseGuildApplicationCommandPermissions(TypedDict): permissions: List[ApplicationCommandPermissions] class PartialGuildApplicationCommandPermissions(BaseGuildApplicationCommandPermissions): id: Snowflake class GuildApplicationCommandPermissions(PartialGuildApplicationCommandPermissions): application_id: Snowflake guild_id: Snowflake InteractionType = Literal[1, 2, 3] class _ApplicationCommandInteractionDataOption(TypedDict): name: str class _ApplicationCommandInteractionDataOptionSubcommand(_ApplicationCommandInteractionDataOption): type: Literal[1, 2] options: List[ApplicationCommandInteractionDataOption] class _ApplicationCommandInteractionDataOptionString(_ApplicationCommandInteractionDataOption): type: Literal[3] value: str class _ApplicationCommandInteractionDataOptionInteger(_ApplicationCommandInteractionDataOption): type: Literal[4] value: int class _ApplicationCommandInteractionDataOptionBoolean(_ApplicationCommandInteractionDataOption): type: Literal[5] value: bool class _ApplicationCommandInteractionDataOptionSnowflake(_ApplicationCommandInteractionDataOption): type: Literal[6, 7, 8, 9] value: Snowflake class _ApplicationCommandInteractionDataOptionNumber(_ApplicationCommandInteractionDataOption): type: Literal[10] value: float ApplicationCommandInteractionDataOption = Union[ _ApplicationCommandInteractionDataOptionString, _ApplicationCommandInteractionDataOptionInteger, _ApplicationCommandInteractionDataOptionSubcommand, _ApplicationCommandInteractionDataOptionBoolean, _ApplicationCommandInteractionDataOptionSnowflake, _ApplicationCommandInteractionDataOptionNumber, ] class ApplicationCommandResolvedPartialChannel(TypedDict): id: Snowflake type: ChannelType permissions: str name: str class ApplicationCommandInteractionDataResolved(TypedDict, total=False): users: Dict[Snowflake, User] members: Dict[Snowflake, Member] roles: Dict[Snowflake, Role] channels: Dict[Snowflake, ApplicationCommandResolvedPartialChannel] class _ApplicationCommandInteractionDataOptional(TypedDict, total=False): options: List[ApplicationCommandInteractionDataOption] resolved: ApplicationCommandInteractionDataResolved target_id: Snowflake type: ApplicationCommandType class ApplicationCommandInteractionData(_ApplicationCommandInteractionDataOptional): id: Snowflake name: str class _ComponentInteractionDataOptional(TypedDict, total=False): values: List[str] class ComponentInteractionData(_ComponentInteractionDataOptional): custom_id: str component_type: ComponentType InteractionData = Union[ApplicationCommandInteractionData, ComponentInteractionData] class _InteractionOptional(TypedDict, total=False): data: InteractionData guild_id: Snowflake channel_id: Snowflake member: Member user: User message: Message class Interaction(_InteractionOptional): id: Snowflake application_id: Snowflake type: InteractionType token: str version: int class InteractionApplicationCommandCallbackData(TypedDict, total=False): tts: bool content: str embeds: List[Embed] allowed_mentions: AllowedMentions flags: int components: List[Component] InteractionResponseType = Literal[1, 4, 5, 6, 7] class _InteractionResponseOptional(TypedDict, total=False): data: InteractionApplicationCommandCallbackData class InteractionResponse(_InteractionResponseOptional): type: InteractionResponseType class MessageInteraction(TypedDict): id: Snowflake type: InteractionType name: str user: User class _EditApplicationCommandOptional(TypedDict, total=False): description: str options: Optional[List[ApplicationCommandOption]] type: ApplicationCommandType class EditApplicationCommand(_EditApplicationCommandOptional): name: str default_permission: bool
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/types/interactions.py
interactions.py
from __future__ import annotations import asyncio import datetime from typing import ( Any, Awaitable, Callable, Generic, List, Optional, Type, TypeVar, Union, ) import aiohttp import discord import inspect import sys import traceback from collections.abc import Sequence from discord.backoff import ExponentialBackoff from discord.utils import MISSING __all__ = ( 'loop', ) T = TypeVar('T') _func = Callable[..., Awaitable[Any]] LF = TypeVar('LF', bound=_func) FT = TypeVar('FT', bound=_func) ET = TypeVar('ET', bound=Callable[[Any, BaseException], Awaitable[Any]]) class SleepHandle: __slots__ = ('future', 'loop', 'handle') def __init__(self, dt: datetime.datetime, *, loop: asyncio.AbstractEventLoop) -> None: self.loop = loop self.future = future = loop.create_future() relative_delta = discord.utils.compute_timedelta(dt) self.handle = loop.call_later(relative_delta, future.set_result, True) def recalculate(self, dt: datetime.datetime) -> None: self.handle.cancel() relative_delta = discord.utils.compute_timedelta(dt) self.handle = self.loop.call_later(relative_delta, self.future.set_result, True) def wait(self) -> asyncio.Future[Any]: return self.future def done(self) -> bool: return self.future.done() def cancel(self) -> None: self.handle.cancel() self.future.cancel() class Loop(Generic[LF]): """A background task helper that abstracts the loop and reconnection logic for you. The main interface to create this is through :func:`loop`. """ def __init__( self, coro: LF, seconds: float, hours: float, minutes: float, time: Union[datetime.time, Sequence[datetime.time]], count: Optional[int], reconnect: bool, loop: asyncio.AbstractEventLoop, ) -> None: self.coro: LF = coro self.reconnect: bool = reconnect self.loop: asyncio.AbstractEventLoop = loop self.count: Optional[int] = count self._current_loop = 0 self._handle: SleepHandle = MISSING self._task: asyncio.Task[None] = MISSING self._injected = None self._valid_exception = ( OSError, discord.GatewayNotFound, discord.ConnectionClosed, aiohttp.ClientError, asyncio.TimeoutError, ) self._before_loop = None self._after_loop = None self._is_being_cancelled = False self._has_failed = False self._stop_next_iteration = False if self.count is not None and self.count <= 0: raise ValueError('count must be greater than 0 or None.') self.change_interval(seconds=seconds, minutes=minutes, hours=hours, time=time) self._last_iteration_failed = False self._last_iteration: datetime.datetime = MISSING self._next_iteration = None if not inspect.iscoroutinefunction(self.coro): raise TypeError(f'Expected coroutine function, not {type(self.coro).__name__!r}.') async def _call_loop_function(self, name: str, *args: Any, **kwargs: Any) -> None: coro = getattr(self, '_' + name) if coro is None: return if self._injected is not None: await coro(self._injected, *args, **kwargs) else: await coro(*args, **kwargs) def _try_sleep_until(self, dt: datetime.datetime): self._handle = SleepHandle(dt=dt, loop=self.loop) return self._handle.wait() async def _loop(self, *args: Any, **kwargs: Any) -> None: backoff = ExponentialBackoff() await self._call_loop_function('before_loop') self._last_iteration_failed = False if self._time is not MISSING: # the time index should be prepared every time the internal loop is started self._prepare_time_index() self._next_iteration = self._get_next_sleep_time() else: self._next_iteration = datetime.datetime.now(datetime.timezone.utc) try: await self._try_sleep_until(self._next_iteration) while True: if not self._last_iteration_failed: self._last_iteration = self._next_iteration self._next_iteration = self._get_next_sleep_time() try: await self.coro(*args, **kwargs) self._last_iteration_failed = False except self._valid_exception: self._last_iteration_failed = True if not self.reconnect: raise await asyncio.sleep(backoff.delay()) else: await self._try_sleep_until(self._next_iteration) if self._stop_next_iteration: return now = datetime.datetime.now(datetime.timezone.utc) if now > self._next_iteration: self._next_iteration = now if self._time is not MISSING: self._prepare_time_index(now) self._current_loop += 1 if self._current_loop == self.count: break except asyncio.CancelledError: self._is_being_cancelled = True raise except Exception as exc: self._has_failed = True await self._call_loop_function('error', exc) raise exc finally: await self._call_loop_function('after_loop') self._handle.cancel() self._is_being_cancelled = False self._current_loop = 0 self._stop_next_iteration = False self._has_failed = False def __get__(self, obj: T, objtype: Type[T]) -> Loop[LF]: if obj is None: return self copy: Loop[LF] = Loop( self.coro, seconds=self._seconds, hours=self._hours, minutes=self._minutes, time=self._time, count=self.count, reconnect=self.reconnect, loop=self.loop, ) copy._injected = obj copy._before_loop = self._before_loop copy._after_loop = self._after_loop copy._error = self._error setattr(obj, self.coro.__name__, copy) return copy @property def seconds(self) -> Optional[float]: """Optional[:class:`float`]: Read-only value for the number of seconds between each iteration. ``None`` if an explicit ``time`` value was passed instead. .. versionadded:: 2.0 """ if self._seconds is not MISSING: return self._seconds @property def minutes(self) -> Optional[float]: """Optional[:class:`float`]: Read-only value for the number of minutes between each iteration. ``None`` if an explicit ``time`` value was passed instead. .. versionadded:: 2.0 """ if self._minutes is not MISSING: return self._minutes @property def hours(self) -> Optional[float]: """Optional[:class:`float`]: Read-only value for the number of hours between each iteration. ``None`` if an explicit ``time`` value was passed instead. .. versionadded:: 2.0 """ if self._hours is not MISSING: return self._hours @property def time(self) -> Optional[List[datetime.time]]: """Optional[List[:class:`datetime.time`]]: Read-only list for the exact times this loop runs at. ``None`` if relative times were passed instead. .. versionadded:: 2.0 """ if self._time is not MISSING: return self._time.copy() @property def current_loop(self) -> int: """:class:`int`: The current iteration of the loop.""" return self._current_loop @property def next_iteration(self) -> Optional[datetime.datetime]: """Optional[:class:`datetime.datetime`]: When the next iteration of the loop will occur. .. versionadded:: 1.3 """ if self._task is MISSING: return None elif self._task and self._task.done() or self._stop_next_iteration: return None return self._next_iteration async def __call__(self, *args: Any, **kwargs: Any) -> Any: r"""|coro| Calls the internal callback that the task holds. .. versionadded:: 1.6 Parameters ------------ \*args The arguments to use. \*\*kwargs The keyword arguments to use. """ if self._injected is not None: args = (self._injected, *args) return await self.coro(*args, **kwargs) def start(self, *args: Any, **kwargs: Any) -> asyncio.Task[None]: r"""Starts the internal task in the event loop. Parameters ------------ \*args The arguments to use. \*\*kwargs The keyword arguments to use. Raises -------- RuntimeError A task has already been launched and is running. Returns --------- :class:`asyncio.Task` The task that has been created. """ if self._task is not MISSING and not self._task.done(): raise RuntimeError('Task is already launched and is not completed.') if self._injected is not None: args = (self._injected, *args) if self.loop is MISSING: self.loop = asyncio.get_event_loop() self._task = self.loop.create_task(self._loop(*args, **kwargs)) return self._task def stop(self) -> None: r"""Gracefully stops the task from running. Unlike :meth:`cancel`\, this allows the task to finish its current iteration before gracefully exiting. .. note:: If the internal function raises an error that can be handled before finishing then it will retry until it succeeds. If this is undesirable, either remove the error handling before stopping via :meth:`clear_exception_types` or use :meth:`cancel` instead. .. versionadded:: 1.2 """ if self._task is not MISSING and not self._task.done(): self._stop_next_iteration = True def _can_be_cancelled(self) -> bool: return bool(not self._is_being_cancelled and self._task and not self._task.done()) def cancel(self) -> None: """Cancels the internal task, if it is running.""" if self._can_be_cancelled(): self._task.cancel() def restart(self, *args: Any, **kwargs: Any) -> None: r"""A convenience method to restart the internal task. .. note:: Due to the way this function works, the task is not returned like :meth:`start`. Parameters ------------ \*args The arguments to use. \*\*kwargs The keyword arguments to use. """ def restart_when_over(fut: Any, *, args: Any = args, kwargs: Any = kwargs) -> None: self._task.remove_done_callback(restart_when_over) self.start(*args, **kwargs) if self._can_be_cancelled(): self._task.add_done_callback(restart_when_over) self._task.cancel() def add_exception_type(self, *exceptions: Type[BaseException]) -> None: r"""Adds exception types to be handled during the reconnect logic. By default the exception types handled are those handled by :meth:`discord.Client.connect`\, which includes a lot of internet disconnection errors. This function is useful if you're interacting with a 3rd party library that raises its own set of exceptions. Parameters ------------ \*exceptions: Type[:class:`BaseException`] An argument list of exception classes to handle. Raises -------- TypeError An exception passed is either not a class or not inherited from :class:`BaseException`. """ for exc in exceptions: if not inspect.isclass(exc): raise TypeError(f'{exc!r} must be a class.') if not issubclass(exc, BaseException): raise TypeError(f'{exc!r} must inherit from BaseException.') self._valid_exception = (*self._valid_exception, *exceptions) def clear_exception_types(self) -> None: """Removes all exception types that are handled. .. note:: This operation obviously cannot be undone! """ self._valid_exception = tuple() def remove_exception_type(self, *exceptions: Type[BaseException]) -> bool: r"""Removes exception types from being handled during the reconnect logic. Parameters ------------ \*exceptions: Type[:class:`BaseException`] An argument list of exception classes to handle. Returns --------- :class:`bool` Whether all exceptions were successfully removed. """ old_length = len(self._valid_exception) self._valid_exception = tuple(x for x in self._valid_exception if x not in exceptions) return len(self._valid_exception) == old_length - len(exceptions) def get_task(self) -> Optional[asyncio.Task[None]]: """Optional[:class:`asyncio.Task`]: Fetches the internal task or ``None`` if there isn't one running.""" return self._task if self._task is not MISSING else None def is_being_cancelled(self) -> bool: """Whether the task is being cancelled.""" return self._is_being_cancelled def failed(self) -> bool: """:class:`bool`: Whether the internal task has failed. .. versionadded:: 1.2 """ return self._has_failed def is_running(self) -> bool: """:class:`bool`: Check if the task is currently running. .. versionadded:: 1.4 """ return not bool(self._task.done()) if self._task is not MISSING else False async def _error(self, *args: Any) -> None: exception: Exception = args[-1] print(f'Unhandled exception in internal background task {self.coro.__name__!r}.', file=sys.stderr) traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr) def before_loop(self, coro: FT) -> FT: """A decorator that registers a coroutine to be called before the loop starts running. This is useful if you want to wait for some bot state before the loop starts, such as :meth:`discord.Client.wait_until_ready`. The coroutine must take no arguments (except ``self`` in a class context). Parameters ------------ coro: :ref:`coroutine <coroutine>` The coroutine to register before the loop runs. Raises ------- TypeError The function was not a coroutine. """ if not inspect.iscoroutinefunction(coro): raise TypeError(f'Expected coroutine function, received {coro.__class__.__name__!r}.') self._before_loop = coro return coro def after_loop(self, coro: FT) -> FT: """A decorator that register a coroutine to be called after the loop finished running. The coroutine must take no arguments (except ``self`` in a class context). .. note:: This coroutine is called even during cancellation. If it is desirable to tell apart whether something was cancelled or not, check to see whether :meth:`is_being_cancelled` is ``True`` or not. Parameters ------------ coro: :ref:`coroutine <coroutine>` The coroutine to register after the loop finishes. Raises ------- TypeError The function was not a coroutine. """ if not inspect.iscoroutinefunction(coro): raise TypeError(f'Expected coroutine function, received {coro.__class__.__name__!r}.') self._after_loop = coro return coro def error(self, coro: ET) -> ET: """A decorator that registers a coroutine to be called if the task encounters an unhandled exception. The coroutine must take only one argument the exception raised (except ``self`` in a class context). By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. .. versionadded:: 1.4 Parameters ------------ coro: :ref:`coroutine <coroutine>` The coroutine to register in the event of an unhandled exception. Raises ------- TypeError The function was not a coroutine. """ if not inspect.iscoroutinefunction(coro): raise TypeError(f'Expected coroutine function, received {coro.__class__.__name__!r}.') self._error = coro # type: ignore return coro def _get_next_sleep_time(self) -> datetime.datetime: if self._sleep is not MISSING: return self._last_iteration + datetime.timedelta(seconds=self._sleep) if self._time_index >= len(self._time): self._time_index = 0 if self._current_loop == 0: # if we're at the last index on the first iteration, we need to sleep until tomorrow return datetime.datetime.combine( datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1), self._time[0] ) next_time = self._time[self._time_index] if self._current_loop == 0: self._time_index += 1 return datetime.datetime.combine(datetime.datetime.now(datetime.timezone.utc), next_time) next_date = self._last_iteration if self._time_index == 0: # we can assume that the earliest time should be scheduled for "tomorrow" next_date += datetime.timedelta(days=1) self._time_index += 1 return datetime.datetime.combine(next_date, next_time) def _prepare_time_index(self, now: datetime.datetime = MISSING) -> None: # now kwarg should be a datetime.datetime representing the time "now" # to calculate the next time index from # pre-condition: self._time is set time_now = ( now if now is not MISSING else datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0) ).timetz() for idx, time in enumerate(self._time): if time >= time_now: self._time_index = idx break else: self._time_index = 0 def _get_time_parameter( self, time: Union[datetime.time, Sequence[datetime.time]], *, dt: Type[datetime.time] = datetime.time, utc: datetime.timezone = datetime.timezone.utc, ) -> List[datetime.time]: if isinstance(time, dt): inner = time if time.tzinfo is not None else time.replace(tzinfo=utc) return [inner] if not isinstance(time, Sequence): raise TypeError( f'Expected datetime.time or a sequence of datetime.time for ``time``, received {type(time)!r} instead.' ) if not time: raise ValueError('time parameter must not be an empty sequence.') ret: List[datetime.time] = [] for index, t in enumerate(time): if not isinstance(t, dt): raise TypeError( f'Expected a sequence of {dt!r} for ``time``, received {type(t).__name__!r} at index {index} instead.' ) ret.append(t if t.tzinfo is not None else t.replace(tzinfo=utc)) ret = sorted(set(ret)) # de-dupe and sort times return ret def change_interval( self, *, seconds: float = 0, minutes: float = 0, hours: float = 0, time: Union[datetime.time, Sequence[datetime.time]] = MISSING, ) -> None: """Changes the interval for the sleep time. .. versionadded:: 1.2 Parameters ------------ seconds: :class:`float` The number of seconds between every iteration. minutes: :class:`float` The number of minutes between every iteration. hours: :class:`float` The number of hours between every iteration. time: Union[:class:`datetime.time`, Sequence[:class:`datetime.time`]] The exact times to run this loop at. Either a non-empty list or a single value of :class:`datetime.time` should be passed. This cannot be used in conjunction with the relative time parameters. .. versionadded:: 2.0 .. note:: Duplicate times will be ignored, and only run once. Raises ------- ValueError An invalid value was given. TypeError An invalid value for the ``time`` parameter was passed, or the ``time`` parameter was passed in conjunction with relative time parameters. """ if time is MISSING: seconds = seconds or 0 minutes = minutes or 0 hours = hours or 0 sleep = seconds + (minutes * 60.0) + (hours * 3600.0) if sleep < 0: raise ValueError('Total number of seconds cannot be less than zero.') self._sleep = sleep self._seconds = float(seconds) self._hours = float(hours) self._minutes = float(minutes) self._time: List[datetime.time] = MISSING else: if any((seconds, minutes, hours)): raise TypeError('Cannot mix explicit time with relative time') self._time = self._get_time_parameter(time) self._sleep = self._seconds = self._minutes = self._hours = MISSING if self.is_running(): if self._time is not MISSING: # prepare the next time index starting from after the last iteration self._prepare_time_index(now=self._last_iteration) self._next_iteration = self._get_next_sleep_time() if not self._handle.done(): # the loop is sleeping, recalculate based on new interval self._handle.recalculate(self._next_iteration) def loop( *, seconds: float = MISSING, minutes: float = MISSING, hours: float = MISSING, time: Union[datetime.time, Sequence[datetime.time]] = MISSING, count: Optional[int] = None, reconnect: bool = True, loop: asyncio.AbstractEventLoop = MISSING, ) -> Callable[[LF], Loop[LF]]: """A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a :class:`Loop`. Parameters ------------ seconds: :class:`float` The number of seconds between every iteration. minutes: :class:`float` The number of minutes between every iteration. hours: :class:`float` The number of hours between every iteration. time: Union[:class:`datetime.time`, Sequence[:class:`datetime.time`]] The exact times to run this loop at. Either a non-empty list or a single value of :class:`datetime.time` should be passed. Timezones are supported. If no timezone is given for the times, it is assumed to represent UTC time. This cannot be used in conjunction with the relative time parameters. .. note:: Duplicate times will be ignored, and only run once. .. versionadded:: 2.0 count: Optional[:class:`int`] The number of loops to do, ``None`` if it should be an infinite loop. reconnect: :class:`bool` Whether to handle errors and restart the task using an exponential back-off algorithm similar to the one used in :meth:`discord.Client.connect`. loop: :class:`asyncio.AbstractEventLoop` The loop to use to register the task, if not given defaults to :func:`asyncio.get_event_loop`. Raises -------- ValueError An invalid value was given. TypeError The function was not a coroutine, an invalid value for the ``time`` parameter was passed, or ``time`` parameter was passed in conjunction with relative time parameters. """ def decorator(func: LF) -> Loop[LF]: return Loop[LF]( func, seconds=seconds, minutes=minutes, hours=hours, count=count, time=time, reconnect=reconnect, loop=loop, ) return decorator
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ext/tasks/__init__.py
__init__.py
from .errors import UnexpectedQuoteError, InvalidEndOfQuotedStringError, ExpectedClosingQuoteError # map from opening quotes to closing quotes _quotes = { '"': '"', "‘": "’", "‚": "‛", "“": "”", "„": "‟", "⹂": "⹂", "「": "」", "『": "』", "〝": "〞", "﹁": "﹂", "﹃": "﹄", """: """, "「": "」", "«": "»", "‹": "›", "《": "》", "〈": "〉", } _all_quotes = set(_quotes.keys()) | set(_quotes.values()) class StringView: def __init__(self, buffer): self.index = 0 self.buffer = buffer self.end = len(buffer) self.previous = 0 @property def current(self): return None if self.eof else self.buffer[self.index] @property def eof(self): return self.index >= self.end def undo(self): self.index = self.previous def skip_ws(self): pos = 0 while not self.eof: try: current = self.buffer[self.index + pos] if not current.isspace(): break pos += 1 except IndexError: break self.previous = self.index self.index += pos return self.previous != self.index def skip_string(self, string): strlen = len(string) if self.buffer[self.index:self.index + strlen] == string: self.previous = self.index self.index += strlen return True return False def read_rest(self): result = self.buffer[self.index:] self.previous = self.index self.index = self.end return result def read(self, n): result = self.buffer[self.index:self.index + n] self.previous = self.index self.index += n return result def get(self): try: result = self.buffer[self.index + 1] except IndexError: result = None self.previous = self.index self.index += 1 return result def get_word(self): pos = 0 while not self.eof: try: current = self.buffer[self.index + pos] if current.isspace(): break pos += 1 except IndexError: break self.previous = self.index result = self.buffer[self.index:self.index + pos] self.index += pos return result def get_quoted_word(self): current = self.current if current is None: return None close_quote = _quotes.get(current) is_quoted = bool(close_quote) if is_quoted: result = [] _escaped_quotes = (current, close_quote) else: result = [current] _escaped_quotes = _all_quotes while not self.eof: current = self.get() if not current: if is_quoted: # unexpected EOF raise ExpectedClosingQuoteError(close_quote) return ''.join(result) # currently we accept strings in the format of "hello world" # to embed a quote inside the string you must escape it: "a \"world\"" if current == '\\': next_char = self.get() if not next_char: # string ends with \ and no character after it if is_quoted: # if we're quoted then we're expecting a closing quote raise ExpectedClosingQuoteError(close_quote) # if we aren't then we just let it through return ''.join(result) if next_char in _escaped_quotes: # escaped quote result.append(next_char) else: # different escape character, ignore it self.undo() result.append(current) continue if not is_quoted and current in _all_quotes: # we aren't quoted raise UnexpectedQuoteError(current) # closing quote if is_quoted and current == close_quote: next_char = self.get() valid_eof = not next_char or next_char.isspace() if not valid_eof: raise InvalidEndOfQuotedStringError(next_char) # we're quoted so it's okay return ''.join(result) if current.isspace() and not is_quoted: # end of word found return ''.join(result) result.append(current) def __repr__(self): return f'<StringView pos: {self.index} prev: {self.previous} end: {self.end} eof: {self.eof}>'
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ext/commands/view.py
view.py
from __future__ import annotations import inspect import re from typing import Any, Dict, Generic, List, Optional, TYPE_CHECKING, TypeVar, Union import discord.abc import discord.utils from discord.message import Message if TYPE_CHECKING: from typing_extensions import ParamSpec from discord.abc import MessageableChannel from discord.guild import Guild from discord.member import Member from discord.state import ConnectionState from discord.user import ClientUser, User from discord.voice_client import VoiceProtocol from .bot import Bot, AutoShardedBot from .cog import Cog from .core import Command from .help import HelpCommand from .view import StringView __all__ = ( 'Context', ) MISSING: Any = discord.utils.MISSING T = TypeVar('T') BotT = TypeVar('BotT', bound="Union[Bot, AutoShardedBot]") CogT = TypeVar('CogT', bound="Cog") if TYPE_CHECKING: P = ParamSpec('P') else: P = TypeVar('P') class Context(discord.abc.Messageable, Generic[BotT]): r"""Represents the context in which a command is being invoked under. This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter. This class implements the :class:`~discord.abc.Messageable` ABC. Attributes ----------- message: :class:`.Message` The message that triggered the command being executed. bot: :class:`.Bot` The bot that contains the command being executed. args: :class:`list` The list of transformed arguments that were passed into the command. If this is accessed during the :func:`.on_command_error` event then this list could be incomplete. kwargs: :class:`dict` A dictionary of transformed arguments that were passed into the command. Similar to :attr:`args`\, if this is accessed in the :func:`.on_command_error` event then this dict could be incomplete. current_parameter: Optional[:class:`inspect.Parameter`] The parameter that is currently being inspected and converted. This is only of use for within converters. .. versionadded:: 2.0 prefix: Optional[:class:`str`] The prefix that was used to invoke the command. command: Optional[:class:`Command`] The command that is being invoked currently. invoked_with: Optional[:class:`str`] The command name that triggered this invocation. Useful for finding out which alias called the command. invoked_parents: List[:class:`str`] The command names of the parents that triggered this invocation. Useful for finding out which aliases called the command. For example in commands ``?a b c test``, the invoked parents are ``['a', 'b', 'c']``. .. versionadded:: 1.7 invoked_subcommand: Optional[:class:`Command`] The subcommand that was invoked. If no valid subcommand was invoked then this is equal to ``None``. subcommand_passed: Optional[:class:`str`] The string that was attempted to call a subcommand. This does not have to point to a valid registered subcommand and could just point to a nonsense string. If nothing was passed to attempt a call to a subcommand then this is set to ``None``. command_failed: :class:`bool` A boolean that indicates if the command failed to be parsed, checked, or invoked. """ def __init__(self, *, message: Message, bot: BotT, view: StringView, args: List[Any] = MISSING, kwargs: Dict[str, Any] = MISSING, prefix: Optional[str] = None, command: Optional[Command] = None, invoked_with: Optional[str] = None, invoked_parents: List[str] = MISSING, invoked_subcommand: Optional[Command] = None, subcommand_passed: Optional[str] = None, command_failed: bool = False, current_parameter: Optional[inspect.Parameter] = None, ): self.message: Message = message self.bot: BotT = bot self.args: List[Any] = args or [] self.kwargs: Dict[str, Any] = kwargs or {} self.prefix: Optional[str] = prefix self.command: Optional[Command] = command self.view: StringView = view self.invoked_with: Optional[str] = invoked_with self.invoked_parents: List[str] = invoked_parents or [] self.invoked_subcommand: Optional[Command] = invoked_subcommand self.subcommand_passed: Optional[str] = subcommand_passed self.command_failed: bool = command_failed self.current_parameter: Optional[inspect.Parameter] = current_parameter self._state: ConnectionState = self.message._state async def invoke(self, command: Command[CogT, P, T], /, *args: P.args, **kwargs: P.kwargs) -> T: r"""|coro| Calls a command with the arguments given. This is useful if you want to just call the callback that a :class:`.Command` holds internally. .. note:: This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function. You must take care in passing the proper arguments when using this function. Parameters ----------- command: :class:`.Command` The command that is going to be called. \*args The arguments to use. \*\*kwargs The keyword arguments to use. Raises ------- TypeError The command argument to invoke is missing. """ return await command(self, *args, **kwargs) async def reinvoke(self, *, call_hooks: bool = False, restart: bool = True) -> None: """|coro| Calls the command again. This is similar to :meth:`~.Context.invoke` except that it bypasses checks, cooldowns, and error handlers. .. note:: If you want to bypass :exc:`.UserInputError` derived exceptions, it is recommended to use the regular :meth:`~.Context.invoke` as it will work more naturally. After all, this will end up using the old arguments the user has used and will thus just fail again. Parameters ------------ call_hooks: :class:`bool` Whether to call the before and after invoke hooks. restart: :class:`bool` Whether to start the call chain from the very beginning or where we left off (i.e. the command that caused the error). The default is to start where we left off. Raises ------- ValueError The context to reinvoke is not valid. """ cmd = self.command view = self.view if cmd is None: raise ValueError('This context is not valid.') # some state to revert to when we're done index, previous = view.index, view.previous invoked_with = self.invoked_with invoked_subcommand = self.invoked_subcommand invoked_parents = self.invoked_parents subcommand_passed = self.subcommand_passed if restart: to_call = cmd.root_parent or cmd view.index = len(self.prefix or '') view.previous = 0 self.invoked_parents = [] self.invoked_with = view.get_word() # advance to get the root command else: to_call = cmd try: await to_call.reinvoke(self, call_hooks=call_hooks) finally: self.command = cmd view.index = index view.previous = previous self.invoked_with = invoked_with self.invoked_subcommand = invoked_subcommand self.invoked_parents = invoked_parents self.subcommand_passed = subcommand_passed @property def valid(self) -> bool: """:class:`bool`: Checks if the invocation context is valid to be invoked with.""" return self.prefix is not None and self.command is not None async def _get_channel(self) -> discord.abc.Messageable: return self.channel @property def clean_prefix(self) -> str: """:class:`str`: The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``. .. versionadded:: 2.0 """ if self.prefix is None: return '' user = self.me # this breaks if the prefix mention is not the bot itself but I # consider this to be an *incredibly* strange use case. I'd rather go # for this common use case rather than waste performance for the # odd one. pattern = re.compile(r"<@!?%s>" % user.id) return pattern.sub("@%s" % user.display_name.replace('\\', r'\\'), self.prefix) @property def cog(self) -> Optional[Cog]: """Optional[:class:`.Cog`]: Returns the cog associated with this context's command. None if it does not exist.""" if self.command is None: return None return self.command.cog @discord.utils.cached_property def guild(self) -> Optional[Guild]: """Optional[:class:`.Guild`]: Returns the guild associated with this context's command. None if not available.""" return self.message.guild @discord.utils.cached_property def channel(self) -> MessageableChannel: """Union[:class:`.abc.Messageable`]: Returns the channel associated with this context's command. Shorthand for :attr:`.Message.channel`. """ return self.message.channel @discord.utils.cached_property def author(self) -> Union[User, Member]: """Union[:class:`~discord.User`, :class:`.Member`]: Returns the author associated with this context's command. Shorthand for :attr:`.Message.author` """ return self.message.author @discord.utils.cached_property def me(self) -> Union[Member, ClientUser]: """Union[:class:`.Member`, :class:`.ClientUser`]: Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts. """ # bot.user will never be None at this point. return self.guild.me if self.guild is not None else self.bot.user # type: ignore @property def voice_client(self) -> Optional[VoiceProtocol]: r"""Optional[:class:`.VoiceProtocol`]: A shortcut to :attr:`.Guild.voice_client`\, if applicable.""" g = self.guild return g.voice_client if g else None async def send_help(self, *args: Any) -> Any: """send_help(entity=<bot>) |coro| Shows the help command for the specified entity if given. The entity can be a command or a cog. If no entity is given, then it'll show help for the entire bot. If the entity is a string, then it looks up whether it's a :class:`Cog` or a :class:`Command`. .. note:: Due to the way this function works, instead of returning something similar to :meth:`~.commands.HelpCommand.command_not_found` this returns :class:`None` on bad input or no help command. Parameters ------------ entity: Optional[Union[:class:`Command`, :class:`Cog`, :class:`str`]] The entity to show help for. Returns -------- Any The result of the help command, if any. """ from .core import Group, Command, wrap_callback from .errors import CommandError bot = self.bot cmd = bot.help_command if cmd is None: return None cmd = cmd.copy() cmd.context = self if len(args) == 0: await cmd.prepare_help_command(self, None) mapping = cmd.get_bot_mapping() injected = wrap_callback(cmd.send_bot_help) try: return await injected(mapping) except CommandError as e: await cmd.on_help_command_error(self, e) return None entity = args[0] if isinstance(entity, str): entity = bot.get_cog(entity) or bot.get_command(entity) if entity is None: return None try: entity.qualified_name except AttributeError: # if we're here then it's not a cog, group, or command. return None await cmd.prepare_help_command(self, entity.qualified_name) try: if hasattr(entity, '__cog_commands__'): injected = wrap_callback(cmd.send_cog_help) return await injected(entity) elif isinstance(entity, Group): injected = wrap_callback(cmd.send_group_help) return await injected(entity) elif isinstance(entity, Command): injected = wrap_callback(cmd.send_command_help) return await injected(entity) else: return None except CommandError as e: await cmd.on_help_command_error(self, e) @discord.utils.copy_doc(Message.reply) async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message: return await self.message.reply(content, **kwargs)
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ext/commands/context.py
context.py
from __future__ import annotations import inspect import discord.utils from typing import Any, Callable, ClassVar, Dict, Generator, List, Optional, TYPE_CHECKING, Tuple, TypeVar, Type from ._types import _BaseCommand if TYPE_CHECKING: from .bot import BotBase from .context import Context from .core import Command __all__ = ( 'CogMeta', 'Cog', ) CogT = TypeVar('CogT', bound='Cog') FuncT = TypeVar('FuncT', bound=Callable[..., Any]) MISSING: Any = discord.utils.MISSING class CogMeta(type): """A metaclass for defining a cog. Note that you should probably not use this directly. It is exposed purely for documentation purposes along with making custom metaclasses to intermix with other metaclasses such as the :class:`abc.ABCMeta` metaclass. For example, to create an abstract cog mixin class, the following would be done. .. code-block:: python3 import abc class CogABCMeta(commands.CogMeta, abc.ABCMeta): pass class SomeMixin(metaclass=abc.ABCMeta): pass class SomeCogMixin(SomeMixin, commands.Cog, metaclass=CogABCMeta): pass .. note:: When passing an attribute of a metaclass that is documented below, note that you must pass it as a keyword-only argument to the class creation like the following example: .. code-block:: python3 class MyCog(commands.Cog, name='My Cog'): pass Attributes ----------- name: :class:`str` The cog name. By default, it is the name of the class with no modification. description: :class:`str` The cog description. By default, it is the cleaned docstring of the class. .. versionadded:: 1.6 command_attrs: :class:`dict` A list of attributes to apply to every command inside this cog. The dictionary is passed into the :class:`Command` options at ``__init__``. If you specify attributes inside the command attribute in the class, it will override the one specified inside this attribute. For example: .. code-block:: python3 class MyCog(commands.Cog, command_attrs=dict(hidden=True)): @commands.command() async def foo(self, ctx): pass # hidden -> True @commands.command(hidden=False) async def bar(self, ctx): pass # hidden -> False """ __cog_name__: str __cog_settings__: Dict[str, Any] __cog_commands__: List[Command] __cog_listeners__: List[Tuple[str, str]] def __new__(cls: Type[CogMeta], *args: Any, **kwargs: Any) -> CogMeta: name, bases, attrs = args attrs['__cog_name__'] = kwargs.pop('name', name) attrs['__cog_settings__'] = kwargs.pop('command_attrs', {}) description = kwargs.pop('description', None) if description is None: description = inspect.cleandoc(attrs.get('__doc__', '')) attrs['__cog_description__'] = description commands = {} listeners = {} no_bot_cog = 'Commands or listeners must not start with cog_ or bot_ (in method {0.__name__}.{1})' new_cls = super().__new__(cls, name, bases, attrs, **kwargs) for base in reversed(new_cls.__mro__): for elem, value in base.__dict__.items(): if elem in commands: del commands[elem] if elem in listeners: del listeners[elem] is_static_method = isinstance(value, staticmethod) if is_static_method: value = value.__func__ if isinstance(value, _BaseCommand): if is_static_method: raise TypeError(f'Command in method {base}.{elem!r} must not be staticmethod.') if elem.startswith(('cog_', 'bot_')): raise TypeError(no_bot_cog.format(base, elem)) commands[elem] = value elif inspect.iscoroutinefunction(value): try: getattr(value, '__cog_listener__') except AttributeError: continue else: if elem.startswith(('cog_', 'bot_')): raise TypeError(no_bot_cog.format(base, elem)) listeners[elem] = value new_cls.__cog_commands__ = list(commands.values()) # this will be copied in Cog.__new__ listeners_as_list = [] for listener in listeners.values(): for listener_name in listener.__cog_listener_names__: # I use __name__ instead of just storing the value so I can inject # the self attribute when the time comes to add them to the bot listeners_as_list.append((listener_name, listener.__name__)) new_cls.__cog_listeners__ = listeners_as_list return new_cls def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args) @classmethod def qualified_name(cls) -> str: return cls.__cog_name__ def _cog_special_method(func: FuncT) -> FuncT: func.__cog_special_method__ = None return func class Cog(metaclass=CogMeta): """The base class that all cogs must inherit from. A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the :ref:`ext_commands_cogs` page. When inheriting from this class, the options shown in :class:`CogMeta` are equally valid here. """ __cog_name__: ClassVar[str] __cog_settings__: ClassVar[Dict[str, Any]] __cog_commands__: ClassVar[List[Command]] __cog_listeners__: ClassVar[List[Tuple[str, str]]] def __new__(cls: Type[CogT], *args: Any, **kwargs: Any) -> CogT: # For issue 426, we need to store a copy of the command objects # since we modify them to inject `self` to them. # To do this, we need to interfere with the Cog creation process. self = super().__new__(cls) cmd_attrs = cls.__cog_settings__ # Either update the command with the cog provided defaults or copy it. # r.e type ignore, type-checker complains about overriding a ClassVar self.__cog_commands__ = tuple(c._update_copy(cmd_attrs) for c in cls.__cog_commands__) # type: ignore lookup = { cmd.qualified_name: cmd for cmd in self.__cog_commands__ } # Update the Command instances dynamically as well for command in self.__cog_commands__: setattr(self, command.callback.__name__, command) parent = command.parent if parent is not None: # Get the latest parent reference parent = lookup[parent.qualified_name] # type: ignore # Update our parent's reference to our self parent.remove_command(command.name) # type: ignore parent.add_command(command) # type: ignore return self def get_commands(self) -> List[Command]: r""" Returns -------- List[:class:`.Command`] A :class:`list` of :class:`.Command`\s that are defined inside this cog. .. note:: This does not include subcommands. """ return [c for c in self.__cog_commands__ if c.parent is None] @property def qualified_name(self) -> str: """:class:`str`: Returns the cog's specified name, not the class name.""" return self.__cog_name__ @property def description(self) -> str: """:class:`str`: Returns the cog's description, typically the cleaned docstring.""" return self.__cog_description__ @description.setter def description(self, description: str) -> None: self.__cog_description__ = description def walk_commands(self) -> Generator[Command, None, None]: """An iterator that recursively walks through this cog's commands and subcommands. Yields ------ Union[:class:`.Command`, :class:`.Group`] A command or group from the cog. """ from .core import GroupMixin for command in self.__cog_commands__: if command.parent is None: yield command if isinstance(command, GroupMixin): yield from command.walk_commands() def get_listeners(self) -> List[Tuple[str, Callable[..., Any]]]: """Returns a :class:`list` of (name, function) listener pairs that are defined in this cog. Returns -------- List[Tuple[:class:`str`, :ref:`coroutine <coroutine>`]] The listeners defined in this cog. """ return [(name, getattr(self, method_name)) for name, method_name in self.__cog_listeners__] @classmethod def _get_overridden_method(cls, method: FuncT) -> Optional[FuncT]: """Return None if the method is not overridden. Otherwise returns the overridden method.""" return getattr(method.__func__, '__cog_special_method__', method) @classmethod def listener(cls, name: str = MISSING) -> Callable[[FuncT], FuncT]: """A decorator that marks a function as a listener. This is the cog equivalent of :meth:`.Bot.listen`. Parameters ------------ name: :class:`str` The name of the event being listened to. If not provided, it defaults to the function's name. Raises -------- TypeError The function is not a coroutine function or a string was not passed as the name. """ if name is not MISSING and not isinstance(name, str): raise TypeError(f'Cog.listener expected str but received {name.__class__.__name__!r} instead.') def decorator(func: FuncT) -> FuncT: actual = func if isinstance(actual, staticmethod): actual = actual.__func__ if not inspect.iscoroutinefunction(actual): raise TypeError('Listener function must be a coroutine function.') actual.__cog_listener__ = True to_assign = name or actual.__name__ try: actual.__cog_listener_names__.append(to_assign) except AttributeError: actual.__cog_listener_names__ = [to_assign] # we have to return `func` instead of `actual` because # we need the type to be `staticmethod` for the metaclass # to pick it up but the metaclass unfurls the function and # thus the assignments need to be on the actual function return func return decorator def has_error_handler(self) -> bool: """:class:`bool`: Checks whether the cog has an error handler. .. versionadded:: 1.7 """ return not hasattr(self.cog_command_error.__func__, '__cog_special_method__') @_cog_special_method def cog_unload(self) -> None: """A special method that is called when the cog gets removed. This function **cannot** be a coroutine. It must be a regular function. Subclasses must replace this if they want special unloading behaviour. """ pass @_cog_special_method def bot_check_once(self, ctx: Context) -> bool: """A special method that registers as a :meth:`.Bot.check_once` check. This function **can** be a coroutine and must take a sole parameter, ``ctx``, to represent the :class:`.Context`. """ return True @_cog_special_method def bot_check(self, ctx: Context) -> bool: """A special method that registers as a :meth:`.Bot.check` check. This function **can** be a coroutine and must take a sole parameter, ``ctx``, to represent the :class:`.Context`. """ return True @_cog_special_method def cog_check(self, ctx: Context) -> bool: """A special method that registers as a :func:`~discord.ext.commands.check` for every command and subcommand in this cog. This function **can** be a coroutine and must take a sole parameter, ``ctx``, to represent the :class:`.Context`. """ return True @_cog_special_method async def cog_command_error(self, ctx: Context, error: Exception) -> None: """A special method that is called whenever an error is dispatched inside this cog. This is similar to :func:`.on_command_error` except only applying to the commands inside this cog. This **must** be a coroutine. Parameters ----------- ctx: :class:`.Context` The invocation context where the error happened. error: :class:`CommandError` The error that happened. """ pass @_cog_special_method async def cog_before_invoke(self, ctx: Context) -> None: """A special method that acts as a cog local pre-invoke hook. This is similar to :meth:`.Command.before_invoke`. This **must** be a coroutine. Parameters ----------- ctx: :class:`.Context` The invocation context. """ pass @_cog_special_method async def cog_after_invoke(self, ctx: Context) -> None: """A special method that acts as a cog local post-invoke hook. This is similar to :meth:`.Command.after_invoke`. This **must** be a coroutine. Parameters ----------- ctx: :class:`.Context` The invocation context. """ pass def _inject(self: CogT, bot: BotBase) -> CogT: cls = self.__class__ # realistically, the only thing that can cause loading errors # is essentially just the command loading, which raises if there are # duplicates. When this condition is met, we want to undo all what # we've added so far for some form of atomic loading. for index, command in enumerate(self.__cog_commands__): command.cog = self if command.parent is None: try: bot.add_command(command) except Exception as e: # undo our additions for to_undo in self.__cog_commands__[:index]: if to_undo.parent is None: bot.remove_command(to_undo.name) raise e # check if we're overriding the default if cls.bot_check is not Cog.bot_check: bot.add_check(self.bot_check) if cls.bot_check_once is not Cog.bot_check_once: bot.add_check(self.bot_check_once, call_once=True) # while Bot.add_listener can raise if it's not a coroutine, # this precondition is already met by the listener decorator # already, thus this should never raise. # Outside of, memory errors and the like... for name, method_name in self.__cog_listeners__: bot.add_listener(getattr(self, method_name), name) return self def _eject(self, bot: BotBase) -> None: cls = self.__class__ try: for command in self.__cog_commands__: if command.parent is None: bot.remove_command(command.name) for _, method_name in self.__cog_listeners__: bot.remove_listener(getattr(self, method_name)) if cls.bot_check is not Cog.bot_check: bot.remove_check(self.bot_check) if cls.bot_check_once is not Cog.bot_check_once: bot.remove_check(self.bot_check_once, call_once=True) finally: try: self.cog_unload() except Exception: pass
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ext/commands/cog.py
cog.py
from __future__ import annotations import re import inspect from typing import ( Any, Dict, Generic, Iterable, Literal, Optional, TYPE_CHECKING, List, Protocol, Type, TypeVar, Tuple, Union, runtime_checkable, ) import discord from .errors import * if TYPE_CHECKING: from .context import Context from discord.message import PartialMessageableChannel __all__ = ( 'Converter', 'ObjectConverter', 'MemberConverter', 'UserConverter', 'MessageConverter', 'PartialMessageConverter', 'TextChannelConverter', 'InviteConverter', 'GuildConverter', 'RoleConverter', 'GameConverter', 'ColourConverter', 'ColorConverter', 'VoiceChannelConverter', 'StageChannelConverter', 'EmojiConverter', 'PartialEmojiConverter', 'CategoryChannelConverter', 'IDConverter', 'StoreChannelConverter', 'ThreadConverter', 'GuildChannelConverter', 'GuildStickerConverter', 'clean_content', 'Greedy', 'run_converters', ) def _get_from_guilds(bot, getter, argument): result = None for guild in bot.guilds: result = getattr(guild, getter)(argument) if result: return result return result _utils_get = discord.utils.get T = TypeVar('T') T_co = TypeVar('T_co', covariant=True) CT = TypeVar('CT', bound=discord.abc.GuildChannel) TT = TypeVar('TT', bound=discord.Thread) @runtime_checkable class Converter(Protocol[T_co]): """The base class of custom converters that require the :class:`.Context` to be passed to be useful. This allows you to implement converters that function similar to the special cased ``discord`` classes. Classes that derive from this should override the :meth:`~.Converter.convert` method to do its conversion logic. This method must be a :ref:`coroutine <coroutine>`. """ async def convert(self, ctx: Context, argument: str) -> T_co: """|coro| The method to override to do conversion logic. If an error is found while converting, it is recommended to raise a :exc:`.CommandError` derived exception as it will properly propagate to the error handlers. Parameters ----------- ctx: :class:`.Context` The invocation context that the argument is being used in. argument: :class:`str` The argument that is being converted. Raises ------- :exc:`.CommandError` A generic exception occurred when converting the argument. :exc:`.BadArgument` The converter failed to convert the argument. """ raise NotImplementedError('Derived classes need to implement this.') _ID_REGEX = re.compile(r'([0-9]{15,20})$') class IDConverter(Converter[T_co]): @staticmethod def _get_id_match(argument): return _ID_REGEX.match(argument) class ObjectConverter(IDConverter[discord.Object]): """Converts to a :class:`~discord.Object`. The argument must follow the valid ID or mention formats (e.g. `<@80088516616269824>`). .. versionadded:: 2.0 The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by member, role, or channel mention. """ async def convert(self, ctx: Context, argument: str) -> discord.Object: match = self._get_id_match(argument) or re.match(r'<(?:@(?:!|&)?|#)([0-9]{15,20})>$', argument) if match is None: raise ObjectNotFound(argument) result = int(match.group(1)) return discord.Object(id=result) class MemberConverter(IDConverter[discord.Member]): """Converts to a :class:`~discord.Member`. All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache. The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by mention. 3. Lookup by name#discrim 4. Lookup by name 5. Lookup by nickname .. versionchanged:: 1.5 Raise :exc:`.MemberNotFound` instead of generic :exc:`.BadArgument` .. versionchanged:: 1.5.1 This converter now lazily fetches members from the gateway and HTTP APIs, optionally caching the result if :attr:`.MemberCacheFlags.joined` is enabled. """ async def query_member_named(self, guild, argument): cache = guild._state.member_cache_flags.joined if len(argument) > 5 and argument[-5] == '#': username, _, discriminator = argument.rpartition('#') members = await guild.query_members(username, limit=100, cache=cache) return discord.utils.get(members, name=username, discriminator=discriminator) else: members = await guild.query_members(argument, limit=100, cache=cache) return discord.utils.find(lambda m: m.name == argument or m.nick == argument, members) async def query_member_by_id(self, bot, guild, user_id): ws = bot._get_websocket(shard_id=guild.shard_id) cache = guild._state.member_cache_flags.joined if ws.is_ratelimited(): # If we're being rate limited on the WS, then fall back to using the HTTP API # So we don't have to wait ~60 seconds for the query to finish try: member = await guild.fetch_member(user_id) except discord.HTTPException: return None if cache: guild._add_member(member) return member # If we're not being rate limited then we can use the websocket to actually query members = await guild.query_members(limit=1, user_ids=[user_id], cache=cache) if not members: return None return members[0] async def convert(self, ctx: Context, argument: str) -> discord.Member: bot = ctx.bot match = self._get_id_match(argument) or re.match(r'<@!?([0-9]{15,20})>$', argument) guild = ctx.guild result = None user_id = None if match is None: # not a mention... if guild: result = guild.get_member_named(argument) else: result = _get_from_guilds(bot, 'get_member_named', argument) else: user_id = int(match.group(1)) if guild: result = guild.get_member(user_id) or _utils_get(ctx.message.mentions, id=user_id) else: result = _get_from_guilds(bot, 'get_member', user_id) if result is None: if guild is None: raise MemberNotFound(argument) if user_id is not None: result = await self.query_member_by_id(bot, guild, user_id) else: result = await self.query_member_named(guild, argument) if not result: raise MemberNotFound(argument) return result class UserConverter(IDConverter[discord.User]): """Converts to a :class:`~discord.User`. All lookups are via the global user cache. The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by mention. 3. Lookup by name#discrim 4. Lookup by name .. versionchanged:: 1.5 Raise :exc:`.UserNotFound` instead of generic :exc:`.BadArgument` .. versionchanged:: 1.6 This converter now lazily fetches users from the HTTP APIs if an ID is passed and it's not available in cache. """ async def convert(self, ctx: Context, argument: str) -> discord.User: match = self._get_id_match(argument) or re.match(r'<@!?([0-9]{15,20})>$', argument) result = None state = ctx._state if match is not None: user_id = int(match.group(1)) result = ctx.bot.get_user(user_id) or _utils_get(ctx.message.mentions, id=user_id) if result is None: try: result = await ctx.bot.fetch_user(user_id) except discord.HTTPException: raise UserNotFound(argument) from None return result arg = argument # Remove the '@' character if this is the first character from the argument if arg[0] == '@': # Remove first character arg = arg[1:] # check for discriminator if it exists, if len(arg) > 5 and arg[-5] == '#': discrim = arg[-4:] name = arg[:-5] predicate = lambda u: u.name == name and u.discriminator == discrim result = discord.utils.find(predicate, state._users.values()) if result is not None: return result predicate = lambda u: u.name == arg result = discord.utils.find(predicate, state._users.values()) if result is None: raise UserNotFound(argument) return result class PartialMessageConverter(Converter[discord.PartialMessage]): """Converts to a :class:`discord.PartialMessage`. .. versionadded:: 1.7 The creation strategy is as follows (in order): 1. By "{channel ID}-{message ID}" (retrieved by shift-clicking on "Copy ID") 2. By message ID (The message is assumed to be in the context channel.) 3. By message URL """ @staticmethod def _get_id_matches(ctx, argument): id_regex = re.compile(r'(?:(?P<channel_id>[0-9]{15,20})-)?(?P<message_id>[0-9]{15,20})$') link_regex = re.compile( r'https?://(?:(ptb|canary|www)\.)?discord(?:app)?\.com/channels/' r'(?P<guild_id>[0-9]{15,20}|@me)' r'/(?P<channel_id>[0-9]{15,20})/(?P<message_id>[0-9]{15,20})/?$' ) match = id_regex.match(argument) or link_regex.match(argument) if not match: raise MessageNotFound(argument) data = match.groupdict() channel_id = discord.utils._get_as_snowflake(data, 'channel_id') message_id = int(data['message_id']) guild_id = data.get('guild_id') if guild_id is None: guild_id = ctx.guild and ctx.guild.id elif guild_id == '@me': guild_id = None else: guild_id = int(guild_id) return guild_id, message_id, channel_id @staticmethod def _resolve_channel(ctx, guild_id, channel_id) -> Optional[PartialMessageableChannel]: if guild_id is not None: guild = ctx.bot.get_guild(guild_id) if guild is not None and channel_id is not None: return guild._resolve_channel(channel_id) # type: ignore else: return None else: return ctx.bot.get_channel(channel_id) if channel_id else ctx.channel async def convert(self, ctx: Context, argument: str) -> discord.PartialMessage: guild_id, message_id, channel_id = self._get_id_matches(ctx, argument) channel = self._resolve_channel(ctx, guild_id, channel_id) if not channel: raise ChannelNotFound(channel_id) return discord.PartialMessage(channel=channel, id=message_id) class MessageConverter(IDConverter[discord.Message]): """Converts to a :class:`discord.Message`. .. versionadded:: 1.1 The lookup strategy is as follows (in order): 1. Lookup by "{channel ID}-{message ID}" (retrieved by shift-clicking on "Copy ID") 2. Lookup by message ID (the message **must** be in the context channel) 3. Lookup by message URL .. versionchanged:: 1.5 Raise :exc:`.ChannelNotFound`, :exc:`.MessageNotFound` or :exc:`.ChannelNotReadable` instead of generic :exc:`.BadArgument` """ async def convert(self, ctx: Context, argument: str) -> discord.Message: guild_id, message_id, channel_id = PartialMessageConverter._get_id_matches(ctx, argument) message = ctx.bot._connection._get_message(message_id) if message: return message channel = PartialMessageConverter._resolve_channel(ctx, guild_id, channel_id) if not channel: raise ChannelNotFound(channel_id) try: return await channel.fetch_message(message_id) except discord.NotFound: raise MessageNotFound(argument) except discord.Forbidden: raise ChannelNotReadable(channel) class GuildChannelConverter(IDConverter[discord.abc.GuildChannel]): """Converts to a :class:`~discord.abc.GuildChannel`. All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache. The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by mention. 3. Lookup by name. .. versionadded:: 2.0 """ async def convert(self, ctx: Context, argument: str) -> discord.abc.GuildChannel: return self._resolve_channel(ctx, argument, 'channels', discord.abc.GuildChannel) @staticmethod def _resolve_channel(ctx: Context, argument: str, attribute: str, type: Type[CT]) -> CT: bot = ctx.bot match = IDConverter._get_id_match(argument) or re.match(r'<#([0-9]{15,20})>$', argument) result = None guild = ctx.guild if match is None: # not a mention if guild: iterable: Iterable[CT] = getattr(guild, attribute) result: Optional[CT] = discord.utils.get(iterable, name=argument) else: def check(c): return isinstance(c, type) and c.name == argument result = discord.utils.find(check, bot.get_all_channels()) else: channel_id = int(match.group(1)) if guild: result = guild.get_channel(channel_id) else: result = _get_from_guilds(bot, 'get_channel', channel_id) if not isinstance(result, type): raise ChannelNotFound(argument) return result @staticmethod def _resolve_thread(ctx: Context, argument: str, attribute: str, type: Type[TT]) -> TT: bot = ctx.bot match = IDConverter._get_id_match(argument) or re.match(r'<#([0-9]{15,20})>$', argument) result = None guild = ctx.guild if match is None: # not a mention if guild: iterable: Iterable[TT] = getattr(guild, attribute) result: Optional[TT] = discord.utils.get(iterable, name=argument) else: thread_id = int(match.group(1)) if guild: result = guild.get_thread(thread_id) if not result or not isinstance(result, type): raise ThreadNotFound(argument) return result class TextChannelConverter(IDConverter[discord.TextChannel]): """Converts to a :class:`~discord.TextChannel`. All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache. The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by mention. 3. Lookup by name .. versionchanged:: 1.5 Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument` """ async def convert(self, ctx: Context, argument: str) -> discord.TextChannel: return GuildChannelConverter._resolve_channel(ctx, argument, 'text_channels', discord.TextChannel) class VoiceChannelConverter(IDConverter[discord.VoiceChannel]): """Converts to a :class:`~discord.VoiceChannel`. All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache. The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by mention. 3. Lookup by name .. versionchanged:: 1.5 Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument` """ async def convert(self, ctx: Context, argument: str) -> discord.VoiceChannel: return GuildChannelConverter._resolve_channel(ctx, argument, 'voice_channels', discord.VoiceChannel) class StageChannelConverter(IDConverter[discord.StageChannel]): """Converts to a :class:`~discord.StageChannel`. .. versionadded:: 1.7 All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache. The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by mention. 3. Lookup by name """ async def convert(self, ctx: Context, argument: str) -> discord.StageChannel: return GuildChannelConverter._resolve_channel(ctx, argument, 'stage_channels', discord.StageChannel) class CategoryChannelConverter(IDConverter[discord.CategoryChannel]): """Converts to a :class:`~discord.CategoryChannel`. All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache. The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by mention. 3. Lookup by name .. versionchanged:: 1.5 Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument` """ async def convert(self, ctx: Context, argument: str) -> discord.CategoryChannel: return GuildChannelConverter._resolve_channel(ctx, argument, 'categories', discord.CategoryChannel) class StoreChannelConverter(IDConverter[discord.StoreChannel]): """Converts to a :class:`~discord.StoreChannel`. All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache. The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by mention. 3. Lookup by name. .. versionadded:: 1.7 """ async def convert(self, ctx: Context, argument: str) -> discord.StoreChannel: return GuildChannelConverter._resolve_channel(ctx, argument, 'channels', discord.StoreChannel) class ThreadConverter(IDConverter[discord.Thread]): """Coverts to a :class:`~discord.Thread`. All lookups are via the local guild. The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by mention. 3. Lookup by name. .. versionadded: 2.0 """ async def convert(self, ctx: Context, argument: str) -> discord.Thread: return GuildChannelConverter._resolve_thread(ctx, argument, 'threads', discord.Thread) class ColourConverter(Converter[discord.Colour]): """Converts to a :class:`~discord.Colour`. .. versionchanged:: 1.5 Add an alias named ColorConverter The following formats are accepted: - ``0x<hex>`` - ``#<hex>`` - ``0x#<hex>`` - ``rgb(<number>, <number>, <number>)`` - Any of the ``classmethod`` in :class:`~discord.Colour` - The ``_`` in the name can be optionally replaced with spaces. Like CSS, ``<number>`` can be either 0-255 or 0-100% and ``<hex>`` can be either a 6 digit hex number or a 3 digit hex shortcut (e.g. #fff). .. versionchanged:: 1.5 Raise :exc:`.BadColourArgument` instead of generic :exc:`.BadArgument` .. versionchanged:: 1.7 Added support for ``rgb`` function and 3-digit hex shortcuts """ RGB_REGEX = re.compile(r'rgb\s*\((?P<r>[0-9]{1,3}%?)\s*,\s*(?P<g>[0-9]{1,3}%?)\s*,\s*(?P<b>[0-9]{1,3}%?)\s*\)') def parse_hex_number(self, argument): arg = ''.join(i * 2 for i in argument) if len(argument) == 3 else argument try: value = int(arg, base=16) if not (0 <= value <= 0xFFFFFF): raise BadColourArgument(argument) except ValueError: raise BadColourArgument(argument) else: return discord.Color(value=value) def parse_rgb_number(self, argument, number): if number[-1] == '%': value = int(number[:-1]) if not (0 <= value <= 100): raise BadColourArgument(argument) return round(255 * (value / 100)) value = int(number) if not (0 <= value <= 255): raise BadColourArgument(argument) return value def parse_rgb(self, argument, *, regex=RGB_REGEX): match = regex.match(argument) if match is None: raise BadColourArgument(argument) red = self.parse_rgb_number(argument, match.group('r')) green = self.parse_rgb_number(argument, match.group('g')) blue = self.parse_rgb_number(argument, match.group('b')) return discord.Color.from_rgb(red, green, blue) async def convert(self, ctx: Context, argument: str) -> discord.Colour: if argument[0] == '#': return self.parse_hex_number(argument[1:]) if argument[0:2] == '0x': rest = argument[2:] # Legacy backwards compatible syntax if rest.startswith('#'): return self.parse_hex_number(rest[1:]) return self.parse_hex_number(rest) arg = argument.lower() if arg[0:3] == 'rgb': return self.parse_rgb(arg) arg = arg.replace(' ', '_') method = getattr(discord.Colour, arg, None) if arg.startswith('from_') or method is None or not inspect.ismethod(method): raise BadColourArgument(arg) return method() ColorConverter = ColourConverter class RoleConverter(IDConverter[discord.Role]): """Converts to a :class:`~discord.Role`. All lookups are via the local guild. If in a DM context, the converter raises :exc:`.NoPrivateMessage` exception. The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by mention. 3. Lookup by name .. versionchanged:: 1.5 Raise :exc:`.RoleNotFound` instead of generic :exc:`.BadArgument` """ async def convert(self, ctx: Context, argument: str) -> discord.Role: guild = ctx.guild if not guild: raise NoPrivateMessage() match = self._get_id_match(argument) or re.match(r'<@&([0-9]{15,20})>$', argument) if match: result = guild.get_role(int(match.group(1))) else: result = discord.utils.get(guild._roles.values(), name=argument) if result is None: raise RoleNotFound(argument) return result class GameConverter(Converter[discord.Game]): """Converts to :class:`~discord.Game`.""" async def convert(self, ctx: Context, argument: str) -> discord.Game: return discord.Game(name=argument) class InviteConverter(Converter[discord.Invite]): """Converts to a :class:`~discord.Invite`. This is done via an HTTP request using :meth:`.Bot.fetch_invite`. .. versionchanged:: 1.5 Raise :exc:`.BadInviteArgument` instead of generic :exc:`.BadArgument` """ async def convert(self, ctx: Context, argument: str) -> discord.Invite: try: invite = await ctx.bot.fetch_invite(argument) return invite except Exception as exc: raise BadInviteArgument(argument) from exc class GuildConverter(IDConverter[discord.Guild]): """Converts to a :class:`~discord.Guild`. The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by name. (There is no disambiguation for Guilds with multiple matching names). .. versionadded:: 1.7 """ async def convert(self, ctx: Context, argument: str) -> discord.Guild: match = self._get_id_match(argument) result = None if match is not None: guild_id = int(match.group(1)) result = ctx.bot.get_guild(guild_id) if result is None: result = discord.utils.get(ctx.bot.guilds, name=argument) if result is None: raise GuildNotFound(argument) return result class EmojiConverter(IDConverter[discord.Emoji]): """Converts to a :class:`~discord.Emoji`. All lookups are done for the local guild first, if available. If that lookup fails, then it checks the client's global cache. The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by extracting ID from the emoji. 3. Lookup by name .. versionchanged:: 1.5 Raise :exc:`.EmojiNotFound` instead of generic :exc:`.BadArgument` """ async def convert(self, ctx: Context, argument: str) -> discord.Emoji: match = self._get_id_match(argument) or re.match(r'<a?:[a-zA-Z0-9\_]{1,32}:([0-9]{15,20})>$', argument) result = None bot = ctx.bot guild = ctx.guild if match is None: # Try to get the emoji by name. Try local guild first. if guild: result = discord.utils.get(guild.emojis, name=argument) if result is None: result = discord.utils.get(bot.emojis, name=argument) else: emoji_id = int(match.group(1)) # Try to look up emoji by id. result = bot.get_emoji(emoji_id) if result is None: raise EmojiNotFound(argument) return result class PartialEmojiConverter(Converter[discord.PartialEmoji]): """Converts to a :class:`~discord.PartialEmoji`. This is done by extracting the animated flag, name and ID from the emoji. .. versionchanged:: 1.5 Raise :exc:`.PartialEmojiConversionFailure` instead of generic :exc:`.BadArgument` """ async def convert(self, ctx: Context, argument: str) -> discord.PartialEmoji: match = re.match(r'<(a?):([a-zA-Z0-9\_]{1,32}):([0-9]{15,20})>$', argument) if match: emoji_animated = bool(match.group(1)) emoji_name = match.group(2) emoji_id = int(match.group(3)) return discord.PartialEmoji.with_state( ctx.bot._connection, animated=emoji_animated, name=emoji_name, id=emoji_id ) raise PartialEmojiConversionFailure(argument) class GuildStickerConverter(IDConverter[discord.GuildSticker]): """Converts to a :class:`~discord.GuildSticker`. All lookups are done for the local guild first, if available. If that lookup fails, then it checks the client's global cache. The lookup strategy is as follows (in order): 1. Lookup by ID. 3. Lookup by name .. versionadded:: 2.0 """ async def convert(self, ctx: Context, argument: str) -> discord.GuildSticker: match = self._get_id_match(argument) result = None bot = ctx.bot guild = ctx.guild if match is None: # Try to get the sticker by name. Try local guild first. if guild: result = discord.utils.get(guild.stickers, name=argument) if result is None: result = discord.utils.get(bot.stickers, name=argument) else: sticker_id = int(match.group(1)) # Try to look up sticker by id. result = bot.get_sticker(sticker_id) if result is None: raise GuildStickerNotFound(argument) return result class clean_content(Converter[str]): """Converts the argument to mention scrubbed version of said content. This behaves similarly to :attr:`~discord.Message.clean_content`. Attributes ------------ fix_channel_mentions: :class:`bool` Whether to clean channel mentions. use_nicknames: :class:`bool` Whether to use nicknames when transforming mentions. escape_markdown: :class:`bool` Whether to also escape special markdown characters. remove_markdown: :class:`bool` Whether to also remove special markdown characters. This option is not supported with ``escape_markdown`` .. versionadded:: 1.7 """ def __init__( self, *, fix_channel_mentions: bool = False, use_nicknames: bool = True, escape_markdown: bool = False, remove_markdown: bool = False, ) -> None: self.fix_channel_mentions = fix_channel_mentions self.use_nicknames = use_nicknames self.escape_markdown = escape_markdown self.remove_markdown = remove_markdown async def convert(self, ctx: Context, argument: str) -> str: msg = ctx.message if ctx.guild: def resolve_member(id: int) -> str: m = _utils_get(msg.mentions, id=id) or ctx.guild.get_member(id) return f'@{m.display_name if self.use_nicknames else m.name}' if m else '@deleted-user' def resolve_role(id: int) -> str: r = _utils_get(msg.role_mentions, id=id) or ctx.guild.get_role(id) return f'@{r.name}' if r else '@deleted-role' else: def resolve_member(id: int) -> str: m = _utils_get(msg.mentions, id=id) or ctx.bot.get_user(id) return f'@{m.name}' if m else '@deleted-user' def resolve_role(id: int) -> str: return '@deleted-role' if self.fix_channel_mentions and ctx.guild: def resolve_channel(id: int) -> str: c = ctx.guild.get_channel(id) return f'#{c.name}' if c else '#deleted-channel' else: def resolve_channel(id: int) -> str: return f'<#{id}>' transforms = { '@': resolve_member, '@!': resolve_member, '#': resolve_channel, '@&': resolve_role, } def repl(match: re.Match) -> str: type = match[1] id = int(match[2]) transformed = transforms[type](id) return transformed result = re.sub(r'<(@[!&]?|#)([0-9]{15,20})>', repl, argument) if self.escape_markdown: result = discord.utils.escape_markdown(result) elif self.remove_markdown: result = discord.utils.remove_markdown(result) # Completely ensure no mentions escape: return discord.utils.escape_mentions(result) class Greedy(List[T]): r"""A special converter that greedily consumes arguments until it can't. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing. When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly. For example, in the following code: .. code-block:: python3 @commands.command() async def test(ctx, numbers: Greedy[int], reason: str): await ctx.send("numbers: {}, reason: {}".format(numbers, reason)) An invocation of ``[p]test 1 2 3 4 5 6 hello`` would pass ``numbers`` with ``[1, 2, 3, 4, 5, 6]`` and ``reason`` with ``hello``\. For more information, check :ref:`ext_commands_special_converters`. """ __slots__ = ('converter',) def __init__(self, *, converter: T): self.converter = converter def __repr__(self): converter = getattr(self.converter, '__name__', repr(self.converter)) return f'Greedy[{converter}]' def __class_getitem__(cls, params: Union[Tuple[T], T]) -> Greedy[T]: if not isinstance(params, tuple): params = (params,) if len(params) != 1: raise TypeError('Greedy[...] only takes a single argument') converter = params[0] origin = getattr(converter, '__origin__', None) args = getattr(converter, '__args__', ()) if not (callable(converter) or isinstance(converter, Converter) or origin is not None): raise TypeError('Greedy[...] expects a type or a Converter instance.') if converter in (str, type(None)) or origin is Greedy: raise TypeError(f'Greedy[{converter.__name__}] is invalid.') if origin is Union and type(None) in args: raise TypeError(f'Greedy[{converter!r}] is invalid.') return cls(converter=converter) def _convert_to_bool(argument: str) -> bool: lowered = argument.lower() if lowered in ('yes', 'y', 'true', 't', '1', 'enable', 'on'): return True elif lowered in ('no', 'n', 'false', 'f', '0', 'disable', 'off'): return False else: raise BadBoolArgument(lowered) def get_converter(param: inspect.Parameter) -> Any: converter = param.annotation if converter is param.empty: if param.default is not param.empty: converter = str if param.default is None else type(param.default) else: converter = str return converter _GenericAlias = type(List[T]) def is_generic_type(tp: Any, *, _GenericAlias: Type = _GenericAlias) -> bool: return isinstance(tp, type) and issubclass(tp, Generic) or isinstance(tp, _GenericAlias) # type: ignore CONVERTER_MAPPING: Dict[Type[Any], Any] = { discord.Object: ObjectConverter, discord.Member: MemberConverter, discord.User: UserConverter, discord.Message: MessageConverter, discord.PartialMessage: PartialMessageConverter, discord.TextChannel: TextChannelConverter, discord.Invite: InviteConverter, discord.Guild: GuildConverter, discord.Role: RoleConverter, discord.Game: GameConverter, discord.Colour: ColourConverter, discord.VoiceChannel: VoiceChannelConverter, discord.StageChannel: StageChannelConverter, discord.Emoji: EmojiConverter, discord.PartialEmoji: PartialEmojiConverter, discord.CategoryChannel: CategoryChannelConverter, discord.StoreChannel: StoreChannelConverter, discord.Thread: ThreadConverter, discord.abc.GuildChannel: GuildChannelConverter, discord.GuildSticker: GuildStickerConverter, } async def _actual_conversion(ctx: Context, converter, argument: str, param: inspect.Parameter): if converter is bool: return _convert_to_bool(argument) try: module = converter.__module__ except AttributeError: pass else: if module is not None and (module.startswith('discord.') and not module.endswith('converter')): converter = CONVERTER_MAPPING.get(converter, converter) try: if inspect.isclass(converter) and issubclass(converter, Converter): if inspect.ismethod(converter.convert): return await converter.convert(ctx, argument) else: return await converter().convert(ctx, argument) elif isinstance(converter, Converter): return await converter.convert(ctx, argument) except CommandError: raise except Exception as exc: raise ConversionError(converter, exc) from exc try: return converter(argument) except CommandError: raise except Exception as exc: try: name = converter.__name__ except AttributeError: name = converter.__class__.__name__ raise BadArgument(f'Converting to "{name}" failed for parameter "{param.name}".') from exc async def run_converters(ctx: Context, converter, argument: str, param: inspect.Parameter): """|coro| Runs converters for a given converter, argument, and parameter. This function does the same work that the library does under the hood. .. versionadded:: 2.0 Parameters ------------ ctx: :class:`Context` The invocation context to run the converters under. converter: Any The converter to run, this corresponds to the annotation in the function. argument: :class:`str` The argument to convert to. param: :class:`inspect.Parameter` The parameter being converted. This is mainly for error reporting. Raises ------- CommandError The converter failed to convert. Returns -------- Any The resulting conversion. """ origin = getattr(converter, '__origin__', None) if origin is Union: errors = [] _NoneType = type(None) union_args = converter.__args__ for conv in union_args: # if we got to this part in the code, then the previous conversions have failed # so we should just undo the view, return the default, and allow parsing to continue # with the other parameters if conv is _NoneType and param.kind != param.VAR_POSITIONAL: ctx.view.undo() return None if param.default is param.empty else param.default try: value = await run_converters(ctx, conv, argument, param) except CommandError as exc: errors.append(exc) else: return value # if we're here, then we failed all the converters raise BadUnionArgument(param, union_args, errors) if origin is Literal: errors = [] conversions = {} literal_args = converter.__args__ for literal in literal_args: literal_type = type(literal) try: value = conversions[literal_type] except KeyError: try: value = await _actual_conversion(ctx, literal_type, argument, param) except CommandError as exc: errors.append(exc) conversions[literal_type] = object() continue else: conversions[literal_type] = value if value == literal: return value # if we're here, then we failed to match all the literals raise BadLiteralArgument(param, literal_args, errors) # This must be the last if-clause in the chain of origin checking # Nearly every type is a generic type within the typing library # So care must be taken to make sure a more specialised origin handle # isn't overwritten by the widest if clause if origin is not None and is_generic_type(converter): converter = origin return await _actual_conversion(ctx, converter, argument, param)
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ext/commands/converter.py
converter.py
from __future__ import annotations from typing import ( Any, Callable, Dict, Generator, Generic, Literal, List, Optional, Union, Set, Tuple, TypeVar, Type, TYPE_CHECKING, overload, ) import asyncio import functools import inspect import datetime import discord from .errors import * from .cooldowns import Cooldown, BucketType, CooldownMapping, MaxConcurrency, DynamicCooldownMapping from .converter import run_converters, get_converter, Greedy from ._types import _BaseCommand from .cog import Cog from .context import Context if TYPE_CHECKING: from typing_extensions import Concatenate, ParamSpec, TypeGuard from discord.message import Message from ._types import ( Coro, CoroFunc, Check, Hook, Error, ) __all__ = ( 'Command', 'Group', 'GroupMixin', 'command', 'group', 'has_role', 'has_permissions', 'has_any_role', 'check', 'check_any', 'before_invoke', 'after_invoke', 'bot_has_role', 'bot_has_permissions', 'bot_has_any_role', 'cooldown', 'dynamic_cooldown', 'max_concurrency', 'dm_only', 'guild_only', 'is_owner', 'is_nsfw', 'has_guild_permissions', 'bot_has_guild_permissions' ) MISSING: Any = discord.utils.MISSING T = TypeVar('T') CogT = TypeVar('CogT', bound='Cog') CommandT = TypeVar('CommandT', bound='Command') ContextT = TypeVar('ContextT', bound='Context') # CHT = TypeVar('CHT', bound='Check') GroupT = TypeVar('GroupT', bound='Group') HookT = TypeVar('HookT', bound='Hook') ErrorT = TypeVar('ErrorT', bound='Error') if TYPE_CHECKING: P = ParamSpec('P') else: P = TypeVar('P') def unwrap_function(function: Callable[..., Any]) -> Callable[..., Any]: partial = functools.partial while True: if hasattr(function, '__wrapped__'): function = function.__wrapped__ elif isinstance(function, partial): function = function.func else: return function def get_signature_parameters(function: Callable[..., Any], globalns: Dict[str, Any]) -> Dict[str, inspect.Parameter]: signature = inspect.signature(function) params = {} cache: Dict[str, Any] = {} eval_annotation = discord.utils.evaluate_annotation for name, parameter in signature.parameters.items(): annotation = parameter.annotation if annotation is parameter.empty: params[name] = parameter continue if annotation is None: params[name] = parameter.replace(annotation=type(None)) continue annotation = eval_annotation(annotation, globalns, globalns, cache) if annotation is Greedy: raise TypeError('Unparameterized Greedy[...] is disallowed in signature.') params[name] = parameter.replace(annotation=annotation) return params def wrap_callback(coro): @functools.wraps(coro) async def wrapped(*args, **kwargs): try: ret = await coro(*args, **kwargs) except CommandError: raise except asyncio.CancelledError: return except Exception as exc: raise CommandInvokeError(exc) from exc return ret return wrapped def hooked_wrapped_callback(command, ctx, coro): @functools.wraps(coro) async def wrapped(*args, **kwargs): try: ret = await coro(*args, **kwargs) except CommandError: ctx.command_failed = True raise except asyncio.CancelledError: ctx.command_failed = True return except Exception as exc: ctx.command_failed = True raise CommandInvokeError(exc) from exc finally: if command._max_concurrency is not None: await command._max_concurrency.release(ctx) await command.call_after_hooks(ctx) return ret return wrapped class _CaseInsensitiveDict(dict): def __contains__(self, k): return super().__contains__(k.casefold()) def __delitem__(self, k): return super().__delitem__(k.casefold()) def __getitem__(self, k): return super().__getitem__(k.casefold()) def get(self, k, default=None): return super().get(k.casefold(), default) def pop(self, k, default=None): return super().pop(k.casefold(), default) def __setitem__(self, k, v): super().__setitem__(k.casefold(), v) class Command(_BaseCommand, Generic[CogT, P, T]): r"""A class that implements the protocol for a bot text command. These are not created manually, instead they are created via the decorator or functional interface. Attributes ----------- name: :class:`str` The name of the command. callback: :ref:`coroutine <coroutine>` The coroutine that is executed when the command is called. help: Optional[:class:`str`] The long help text for the command. brief: Optional[:class:`str`] The short help text for the command. usage: Optional[:class:`str`] A replacement for arguments in the default help text. aliases: Union[List[:class:`str`], Tuple[:class:`str`]] The list of aliases the command can be invoked under. enabled: :class:`bool` A boolean that indicates if the command is currently enabled. If the command is invoked while it is disabled, then :exc:`.DisabledCommand` is raised to the :func:`.on_command_error` event. Defaults to ``True``. parent: Optional[:class:`Group`] The parent group that this command belongs to. ``None`` if there isn't one. cog: Optional[:class:`Cog`] The cog that this command belongs to. ``None`` if there isn't one. checks: List[Callable[[:class:`.Context`], :class:`bool`]] A list of predicates that verifies if the command could be executed with the given :class:`.Context` as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from :exc:`.CommandError` should be used. Note that if the checks fail then :exc:`.CheckFailure` exception is raised to the :func:`.on_command_error` event. description: :class:`str` The message prefixed into the default help command. hidden: :class:`bool` If ``True``\, the default help command does not show this in the help output. rest_is_raw: :class:`bool` If ``False`` and a keyword-only argument is provided then the keyword only argument is stripped and handled as if it was a regular argument that handles :exc:`.MissingRequiredArgument` and default values in a regular matter rather than passing the rest completely raw. If ``True`` then the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults to ``False``. invoked_subcommand: Optional[:class:`Command`] The subcommand that was invoked, if any. require_var_positional: :class:`bool` If ``True`` and a variadic positional argument is specified, requires the user to specify at least one argument. Defaults to ``False``. .. versionadded:: 1.5 ignore_extra: :class:`bool` If ``True``\, ignores extraneous strings passed to a command if all its requirements are met (e.g. ``?foo a b c`` when only expecting ``a`` and ``b``). Otherwise :func:`.on_command_error` and local error handlers are called with :exc:`.TooManyArguments`. Defaults to ``True``. cooldown_after_parsing: :class:`bool` If ``True``\, cooldown processing is done after argument parsing, which calls converters. If ``False`` then cooldown processing is done first and then the converters are called second. Defaults to ``False``. extras: :class:`dict` A dict of user provided extras to attach to the Command. .. note:: This object may be copied by the library. .. versionadded:: 2.0 """ __original_kwargs__: Dict[str, Any] def __new__(cls: Type[CommandT], *args: Any, **kwargs: Any) -> CommandT: # if you're wondering why this is done, it's because we need to ensure # we have a complete original copy of **kwargs even for classes that # mess with it by popping before delegating to the subclass __init__. # In order to do this, we need to control the instance creation and # inject the original kwargs through __new__ rather than doing it # inside __init__. self = super().__new__(cls) # we do a shallow copy because it's probably the most common use case. # this could potentially break if someone modifies a list or something # while it's in movement, but for now this is the cheapest and # fastest way to do what we want. self.__original_kwargs__ = kwargs.copy() return self def __init__(self, func: Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]], ], **kwargs: Any): if not asyncio.iscoroutinefunction(func): raise TypeError('Callback must be a coroutine.') name = kwargs.get('name') or func.__name__ if not isinstance(name, str): raise TypeError('Name of a command must be a string.') self.name: str = name self.callback = func self.enabled: bool = kwargs.get('enabled', True) help_doc = kwargs.get('help') if help_doc is not None: help_doc = inspect.cleandoc(help_doc) else: help_doc = inspect.getdoc(func) if isinstance(help_doc, bytes): help_doc = help_doc.decode('utf-8') self.help: Optional[str] = help_doc self.brief: Optional[str] = kwargs.get('brief') self.usage: Optional[str] = kwargs.get('usage') self.rest_is_raw: bool = kwargs.get('rest_is_raw', False) self.aliases: Union[List[str], Tuple[str]] = kwargs.get('aliases', []) self.extras: Dict[str, Any] = kwargs.get('extras', {}) if not isinstance(self.aliases, (list, tuple)): raise TypeError("Aliases of a command must be a list or a tuple of strings.") self.description: str = inspect.cleandoc(kwargs.get('description', '')) self.hidden: bool = kwargs.get('hidden', False) try: checks = func.__commands_checks__ checks.reverse() except AttributeError: checks = kwargs.get('checks', []) self.checks: List[Check] = checks try: cooldown = func.__commands_cooldown__ except AttributeError: cooldown = kwargs.get('cooldown') if cooldown is None: buckets = CooldownMapping(cooldown, BucketType.default) elif isinstance(cooldown, CooldownMapping): buckets = cooldown else: raise TypeError("Cooldown must be a an instance of CooldownMapping or None.") self._buckets: CooldownMapping = buckets try: max_concurrency = func.__commands_max_concurrency__ except AttributeError: max_concurrency = kwargs.get('max_concurrency') self._max_concurrency: Optional[MaxConcurrency] = max_concurrency self.require_var_positional: bool = kwargs.get('require_var_positional', False) self.ignore_extra: bool = kwargs.get('ignore_extra', True) self.cooldown_after_parsing: bool = kwargs.get('cooldown_after_parsing', False) self.cog: Optional[CogT] = None # bandaid for the fact that sometimes parent can be the bot instance parent = kwargs.get('parent') self.parent: Optional[GroupMixin] = parent if isinstance(parent, _BaseCommand) else None # type: ignore self._before_invoke: Optional[Hook] = None try: before_invoke = func.__before_invoke__ except AttributeError: pass else: self.before_invoke(before_invoke) self._after_invoke: Optional[Hook] = None try: after_invoke = func.__after_invoke__ except AttributeError: pass else: self.after_invoke(after_invoke) @property def callback(self) -> Union[ Callable[Concatenate[CogT, Context, P], Coro[T]], Callable[Concatenate[Context, P], Coro[T]], ]: return self._callback @callback.setter def callback(self, function: Union[ Callable[Concatenate[CogT, Context, P], Coro[T]], Callable[Concatenate[Context, P], Coro[T]], ]) -> None: self._callback = function unwrap = unwrap_function(function) self.module = unwrap.__module__ try: globalns = unwrap.__globals__ except AttributeError: globalns = {} self.params = get_signature_parameters(function, globalns) def add_check(self, func: Check) -> None: """Adds a check to the command. This is the non-decorator interface to :func:`.check`. .. versionadded:: 1.3 Parameters ----------- func The function that will be used as a check. """ self.checks.append(func) def remove_check(self, func: Check) -> None: """Removes a check from the command. This function is idempotent and will not raise an exception if the function is not in the command's checks. .. versionadded:: 1.3 Parameters ----------- func The function to remove from the checks. """ try: self.checks.remove(func) except ValueError: pass def update(self, **kwargs: Any) -> None: """Updates :class:`Command` instance with updated attribute. This works similarly to the :func:`.command` decorator in terms of parameters in that they are passed to the :class:`Command` or subclass constructors, sans the name and callback. """ self.__init__(self.callback, **dict(self.__original_kwargs__, **kwargs)) async def __call__(self, context: Context, *args: P.args, **kwargs: P.kwargs) -> T: """|coro| Calls the internal callback that the command holds. .. note:: This bypasses all mechanisms -- including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function. .. versionadded:: 1.3 """ if self.cog is not None: return await self.callback(self.cog, context, *args, **kwargs) # type: ignore else: return await self.callback(context, *args, **kwargs) # type: ignore def _ensure_assignment_on_copy(self, other: CommandT) -> CommandT: other._before_invoke = self._before_invoke other._after_invoke = self._after_invoke if self.checks != other.checks: other.checks = self.checks.copy() if self._buckets.valid and not other._buckets.valid: other._buckets = self._buckets.copy() if self._max_concurrency != other._max_concurrency: # _max_concurrency won't be None at this point other._max_concurrency = self._max_concurrency.copy() # type: ignore try: other.on_error = self.on_error except AttributeError: pass return other def copy(self: CommandT) -> CommandT: """Creates a copy of this command. Returns -------- :class:`Command` A new instance of this command. """ ret = self.__class__(self.callback, **self.__original_kwargs__) return self._ensure_assignment_on_copy(ret) def _update_copy(self: CommandT, kwargs: Dict[str, Any]) -> CommandT: if kwargs: kw = kwargs.copy() kw.update(self.__original_kwargs__) copy = self.__class__(self.callback, **kw) return self._ensure_assignment_on_copy(copy) else: return self.copy() async def dispatch_error(self, ctx: Context, error: Exception) -> None: ctx.command_failed = True cog = self.cog try: coro = self.on_error except AttributeError: pass else: injected = wrap_callback(coro) if cog is not None: await injected(cog, ctx, error) else: await injected(ctx, error) try: if cog is not None: local = Cog._get_overridden_method(cog.cog_command_error) if local is not None: wrapped = wrap_callback(local) await wrapped(ctx, error) finally: ctx.bot.dispatch('command_error', ctx, error) async def transform(self, ctx: Context, param: inspect.Parameter) -> Any: required = param.default is param.empty converter = get_converter(param) consume_rest_is_special = param.kind == param.KEYWORD_ONLY and not self.rest_is_raw view = ctx.view view.skip_ws() # The greedy converter is simple -- it keeps going until it fails in which case, # it undos the view ready for the next parameter to use instead if isinstance(converter, Greedy): if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY): return await self._transform_greedy_pos(ctx, param, required, converter.converter) elif param.kind == param.VAR_POSITIONAL: return await self._transform_greedy_var_pos(ctx, param, converter.converter) else: # if we're here, then it's a KEYWORD_ONLY param type # since this is mostly useless, we'll helpfully transform Greedy[X] # into just X and do the parsing that way. converter = converter.converter if view.eof: if param.kind == param.VAR_POSITIONAL: raise RuntimeError() # break the loop if required: if self._is_typing_optional(param.annotation): return None if hasattr(converter, '__commands_is_flag__') and converter._can_be_constructible(): return await converter._construct_default(ctx) raise MissingRequiredArgument(param) return param.default previous = view.index if consume_rest_is_special: argument = view.read_rest().strip() else: try: argument = view.get_quoted_word() except ArgumentParsingError as exc: if self._is_typing_optional(param.annotation): view.index = previous return None else: raise exc view.previous = previous # type-checker fails to narrow argument return await run_converters(ctx, converter, argument, param) # type: ignore async def _transform_greedy_pos(self, ctx: Context, param: inspect.Parameter, required: bool, converter: Any) -> Any: view = ctx.view result = [] while not view.eof: # for use with a manual undo previous = view.index view.skip_ws() try: argument = view.get_quoted_word() value = await run_converters(ctx, converter, argument, param) # type: ignore except (CommandError, ArgumentParsingError): view.index = previous break else: result.append(value) if not result and not required: return param.default return result async def _transform_greedy_var_pos(self, ctx: Context, param: inspect.Parameter, converter: Any) -> Any: view = ctx.view previous = view.index try: argument = view.get_quoted_word() value = await run_converters(ctx, converter, argument, param) # type: ignore except (CommandError, ArgumentParsingError): view.index = previous raise RuntimeError() from None # break loop else: return value @property def clean_params(self) -> Dict[str, inspect.Parameter]: """Dict[:class:`str`, :class:`inspect.Parameter`]: Retrieves the parameter dictionary without the context or self parameters. Useful for inspecting signature. """ result = self.params.copy() if self.cog is not None: # first parameter is self try: del result[next(iter(result))] except StopIteration: raise ValueError("missing 'self' parameter") from None try: # first/second parameter is context del result[next(iter(result))] except StopIteration: raise ValueError("missing 'context' parameter") from None return result @property def full_parent_name(self) -> str: """:class:`str`: Retrieves the fully qualified parent command name. This the base command name required to execute it. For example, in ``?one two three`` the parent name would be ``one two``. """ entries = [] command = self # command.parent is type-hinted as GroupMixin some attributes are resolved via MRO while command.parent is not None: # type: ignore command = command.parent # type: ignore entries.append(command.name) # type: ignore return ' '.join(reversed(entries)) @property def parents(self) -> List[Group]: """List[:class:`Group`]: Retrieves the parents of this command. If the command has no parents then it returns an empty :class:`list`. For example in commands ``?a b c test``, the parents are ``[c, b, a]``. .. versionadded:: 1.1 """ entries = [] command = self while command.parent is not None: # type: ignore command = command.parent # type: ignore entries.append(command) return entries @property def root_parent(self) -> Optional[Group]: """Optional[:class:`Group`]: Retrieves the root parent of this command. If the command has no parents then it returns ``None``. For example in commands ``?a b c test``, the root parent is ``a``. """ if not self.parent: return None return self.parents[-1] @property def qualified_name(self) -> str: """:class:`str`: Retrieves the fully qualified command name. This is the full parent name with the command name as well. For example, in ``?one two three`` the qualified name would be ``one two three``. """ parent = self.full_parent_name if parent: return parent + ' ' + self.name else: return self.name def __str__(self) -> str: return self.qualified_name async def _parse_arguments(self, ctx: Context) -> None: ctx.args = [ctx] if self.cog is None else [self.cog, ctx] ctx.kwargs = {} args = ctx.args kwargs = ctx.kwargs view = ctx.view iterator = iter(self.params.items()) if self.cog is not None: # we have 'self' as the first parameter so just advance # the iterator and resume parsing try: next(iterator) except StopIteration: raise discord.ClientException(f'Callback for {self.name} command is missing "self" parameter.') # next we have the 'ctx' as the next parameter try: next(iterator) except StopIteration: raise discord.ClientException(f'Callback for {self.name} command is missing "ctx" parameter.') for name, param in iterator: ctx.current_parameter = param if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY): transformed = await self.transform(ctx, param) args.append(transformed) elif param.kind == param.KEYWORD_ONLY: # kwarg only param denotes "consume rest" semantics if self.rest_is_raw: converter = get_converter(param) argument = view.read_rest() kwargs[name] = await run_converters(ctx, converter, argument, param) else: kwargs[name] = await self.transform(ctx, param) break elif param.kind == param.VAR_POSITIONAL: if view.eof and self.require_var_positional: raise MissingRequiredArgument(param) while not view.eof: try: transformed = await self.transform(ctx, param) args.append(transformed) except RuntimeError: break if not self.ignore_extra and not view.eof: raise TooManyArguments('Too many arguments passed to ' + self.qualified_name) async def call_before_hooks(self, ctx: Context) -> None: # now that we're done preparing we can call the pre-command hooks # first, call the command local hook: cog = self.cog if self._before_invoke is not None: # should be cog if @commands.before_invoke is used instance = getattr(self._before_invoke, '__self__', cog) # __self__ only exists for methods, not functions # however, if @command.before_invoke is used, it will be a function if instance: await self._before_invoke(instance, ctx) # type: ignore else: await self._before_invoke(ctx) # type: ignore # call the cog local hook if applicable: if cog is not None: hook = Cog._get_overridden_method(cog.cog_before_invoke) if hook is not None: await hook(ctx) # call the bot global hook if necessary hook = ctx.bot._before_invoke if hook is not None: await hook(ctx) async def call_after_hooks(self, ctx: Context) -> None: cog = self.cog if self._after_invoke is not None: instance = getattr(self._after_invoke, '__self__', cog) if instance: await self._after_invoke(instance, ctx) # type: ignore else: await self._after_invoke(ctx) # type: ignore # call the cog local hook if applicable: if cog is not None: hook = Cog._get_overridden_method(cog.cog_after_invoke) if hook is not None: await hook(ctx) hook = ctx.bot._after_invoke if hook is not None: await hook(ctx) def _prepare_cooldowns(self, ctx: Context) -> None: if self._buckets.valid: dt = ctx.message.edited_at or ctx.message.created_at current = dt.replace(tzinfo=datetime.timezone.utc).timestamp() bucket = self._buckets.get_bucket(ctx.message, current) if bucket is not None: retry_after = bucket.update_rate_limit(current) if retry_after: raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore async def prepare(self, ctx: Context) -> None: ctx.command = self if not await self.can_run(ctx): raise CheckFailure(f'The check functions for command {self.qualified_name} failed.') if self._max_concurrency is not None: # For this application, context can be duck-typed as a Message await self._max_concurrency.acquire(ctx) # type: ignore try: if self.cooldown_after_parsing: await self._parse_arguments(ctx) self._prepare_cooldowns(ctx) else: self._prepare_cooldowns(ctx) await self._parse_arguments(ctx) await self.call_before_hooks(ctx) except: if self._max_concurrency is not None: await self._max_concurrency.release(ctx) # type: ignore raise def is_on_cooldown(self, ctx: Context) -> bool: """Checks whether the command is currently on cooldown. Parameters ----------- ctx: :class:`.Context` The invocation context to use when checking the commands cooldown status. Returns -------- :class:`bool` A boolean indicating if the command is on cooldown. """ if not self._buckets.valid: return False bucket = self._buckets.get_bucket(ctx.message) dt = ctx.message.edited_at or ctx.message.created_at current = dt.replace(tzinfo=datetime.timezone.utc).timestamp() return bucket.get_tokens(current) == 0 def reset_cooldown(self, ctx: Context) -> None: """Resets the cooldown on this command. Parameters ----------- ctx: :class:`.Context` The invocation context to reset the cooldown under. """ if self._buckets.valid: bucket = self._buckets.get_bucket(ctx.message) bucket.reset() def get_cooldown_retry_after(self, ctx: Context) -> float: """Retrieves the amount of seconds before this command can be tried again. .. versionadded:: 1.4 Parameters ----------- ctx: :class:`.Context` The invocation context to retrieve the cooldown from. Returns -------- :class:`float` The amount of time left on this command's cooldown in seconds. If this is ``0.0`` then the command isn't on cooldown. """ if self._buckets.valid: bucket = self._buckets.get_bucket(ctx.message) dt = ctx.message.edited_at or ctx.message.created_at current = dt.replace(tzinfo=datetime.timezone.utc).timestamp() return bucket.get_retry_after(current) return 0.0 async def invoke(self, ctx: Context) -> None: await self.prepare(ctx) # terminate the invoked_subcommand chain. # since we're in a regular command (and not a group) then # the invoked subcommand is None. ctx.invoked_subcommand = None ctx.subcommand_passed = None injected = hooked_wrapped_callback(self, ctx, self.callback) await injected(*ctx.args, **ctx.kwargs) async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None: ctx.command = self await self._parse_arguments(ctx) if call_hooks: await self.call_before_hooks(ctx) ctx.invoked_subcommand = None try: await self.callback(*ctx.args, **ctx.kwargs) # type: ignore except: ctx.command_failed = True raise finally: if call_hooks: await self.call_after_hooks(ctx) def error(self, coro: ErrorT) -> ErrorT: """A decorator that registers a coroutine as a local error handler. A local error handler is an :func:`.on_command_error` event limited to a single command. However, the :func:`.on_command_error` is still invoked afterwards as the catch-all. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the local error handler. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The error handler must be a coroutine.') self.on_error: Error = coro return coro def has_error_handler(self) -> bool: """:class:`bool`: Checks whether the command has an error handler registered. .. versionadded:: 1.7 """ return hasattr(self, 'on_error') def before_invoke(self, coro: HookT) -> HookT: """A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required. This pre-invoke hook takes a sole parameter, a :class:`.Context`. See :meth:`.Bot.before_invoke` for more info. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the pre-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke = coro return coro def after_invoke(self, coro: HookT) -> HookT: """A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required. This post-invoke hook takes a sole parameter, a :class:`.Context`. See :meth:`.Bot.after_invoke` for more info. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the post-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must be a coroutine.') self._after_invoke = coro return coro @property def cog_name(self) -> Optional[str]: """Optional[:class:`str`]: The name of the cog this command belongs to, if any.""" return type(self.cog).__cog_name__ if self.cog is not None else None @property def short_doc(self) -> str: """:class:`str`: Gets the "short" documentation of a command. By default, this is the :attr:`.brief` attribute. If that lookup leads to an empty string then the first line of the :attr:`.help` attribute is used instead. """ if self.brief is not None: return self.brief if self.help is not None: return self.help.split('\n', 1)[0] return '' def _is_typing_optional(self, annotation: Union[T, Optional[T]]) -> TypeGuard[Optional[T]]: return getattr(annotation, '__origin__', None) is Union and type(None) in annotation.__args__ # type: ignore @property def signature(self) -> str: """:class:`str`: Returns a POSIX-like signature useful for help command output.""" if self.usage is not None: return self.usage params = self.clean_params if not params: return '' result = [] for name, param in params.items(): greedy = isinstance(param.annotation, Greedy) optional = False # postpone evaluation of if it's an optional argument # for typing.Literal[...], typing.Optional[typing.Literal[...]], and Greedy[typing.Literal[...]], the # parameter signature is a literal list of it's values annotation = param.annotation.converter if greedy else param.annotation origin = getattr(annotation, '__origin__', None) if not greedy and origin is Union: none_cls = type(None) union_args = annotation.__args__ optional = union_args[-1] is none_cls if len(union_args) == 2 and optional: annotation = union_args[0] origin = getattr(annotation, '__origin__', None) if origin is Literal: name = '|'.join(f'"{v}"' if isinstance(v, str) else str(v) for v in annotation.__args__) if param.default is not param.empty: # We don't want None or '' to trigger the [name=value] case and instead it should # do [name] since [name=None] or [name=] are not exactly useful for the user. should_print = param.default if isinstance(param.default, str) else param.default is not None if should_print: result.append(f'[{name}={param.default}]' if not greedy else f'[{name}={param.default}]...') continue else: result.append(f'[{name}]') elif param.kind == param.VAR_POSITIONAL: if self.require_var_positional: result.append(f'<{name}...>') else: result.append(f'[{name}...]') elif greedy: result.append(f'[{name}]...') elif optional: result.append(f'[{name}]') else: result.append(f'<{name}>') return ' '.join(result) async def can_run(self, ctx: Context) -> bool: """|coro| Checks if the command can be executed by checking all the predicates inside the :attr:`~Command.checks` attribute. This also checks whether the command is disabled. .. versionchanged:: 1.3 Checks whether the command is disabled or not Parameters ----------- ctx: :class:`.Context` The ctx of the command currently being invoked. Raises ------- :class:`CommandError` Any command error that was raised during a check call will be propagated by this function. Returns -------- :class:`bool` A boolean indicating if the command can be invoked. """ if not self.enabled: raise DisabledCommand(f'{self.name} command is disabled') original = ctx.command ctx.command = self try: if not await ctx.bot.can_run(ctx): raise CheckFailure(f'The global check functions for command {self.qualified_name} failed.') cog = self.cog if cog is not None: local_check = Cog._get_overridden_method(cog.cog_check) if local_check is not None: ret = await discord.utils.maybe_coroutine(local_check, ctx) if not ret: return False predicates = self.checks if not predicates: # since we have no checks, then we just return True. return True return await discord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore finally: ctx.command = original class GroupMixin(Generic[CogT]): """A mixin that implements common functionality for classes that behave similar to :class:`.Group` and are allowed to register commands. Attributes ----------- all_commands: :class:`dict` A mapping of command name to :class:`.Command` objects. case_insensitive: :class:`bool` Whether the commands should be case insensitive. Defaults to ``False``. """ def __init__(self, *args: Any, **kwargs: Any) -> None: case_insensitive = kwargs.get('case_insensitive', False) self.all_commands: Dict[str, Command[CogT, Any, Any]] = _CaseInsensitiveDict() if case_insensitive else {} self.case_insensitive: bool = case_insensitive super().__init__(*args, **kwargs) @property def commands(self) -> Set[Command[CogT, Any, Any]]: """Set[:class:`.Command`]: A unique set of commands without aliases that are registered.""" return set(self.all_commands.values()) def recursively_remove_all_commands(self) -> None: for command in self.all_commands.copy().values(): if isinstance(command, GroupMixin): command.recursively_remove_all_commands() self.remove_command(command.name) def add_command(self, command: Command[CogT, Any, Any]) -> None: """Adds a :class:`.Command` into the internal list of commands. This is usually not called, instead the :meth:`~.GroupMixin.command` or :meth:`~.GroupMixin.group` shortcut decorators are used instead. .. versionchanged:: 1.4 Raise :exc:`.CommandRegistrationError` instead of generic :exc:`.ClientException` Parameters ----------- command: :class:`Command` The command to add. Raises ------- :exc:`.CommandRegistrationError` If the command or its alias is already registered by different command. TypeError If the command passed is not a subclass of :class:`.Command`. """ if not isinstance(command, Command): raise TypeError('The command passed must be a subclass of Command') if isinstance(self, Command): command.parent = self if command.name in self.all_commands: raise CommandRegistrationError(command.name) self.all_commands[command.name] = command for alias in command.aliases: if alias in self.all_commands: self.remove_command(command.name) raise CommandRegistrationError(alias, alias_conflict=True) self.all_commands[alias] = command def remove_command(self, name: str) -> Optional[Command[CogT, Any, Any]]: """Remove a :class:`.Command` from the internal list of commands. This could also be used as a way to remove aliases. Parameters ----------- name: :class:`str` The name of the command to remove. Returns -------- Optional[:class:`.Command`] The command that was removed. If the name is not valid then ``None`` is returned instead. """ command = self.all_commands.pop(name, None) # does not exist if command is None: return None if name in command.aliases: # we're removing an alias so we don't want to remove the rest return command # we're not removing the alias so let's delete the rest of them. for alias in command.aliases: cmd = self.all_commands.pop(alias, None) # in the case of a CommandRegistrationError, an alias might conflict # with an already existing command. If this is the case, we want to # make sure the pre-existing command is not removed. if cmd is not None and cmd != command: self.all_commands[alias] = cmd return command def walk_commands(self) -> Generator[Command[CogT, Any, Any], None, None]: """An iterator that recursively walks through all commands and subcommands. .. versionchanged:: 1.4 Duplicates due to aliases are no longer returned Yields ------ Union[:class:`.Command`, :class:`.Group`] A command or group from the internal list of commands. """ for command in self.commands: yield command if isinstance(command, GroupMixin): yield from command.walk_commands() def get_command(self, name: str) -> Optional[Command[CogT, Any, Any]]: """Get a :class:`.Command` from the internal list of commands. This could also be used as a way to get aliases. The name could be fully qualified (e.g. ``'foo bar'``) will get the subcommand ``bar`` of the group command ``foo``. If a subcommand is not found then ``None`` is returned just as usual. Parameters ----------- name: :class:`str` The name of the command to get. Returns -------- Optional[:class:`Command`] The command that was requested. If not found, returns ``None``. """ # fast path, no space in name. if ' ' not in name: return self.all_commands.get(name) names = name.split() if not names: return None obj = self.all_commands.get(names[0]) if not isinstance(obj, GroupMixin): return obj for name in names[1:]: try: obj = obj.all_commands[name] # type: ignore except (AttributeError, KeyError): return None return obj @overload def command( self, name: str = ..., cls: Type[Command[CogT, P, T]] = ..., *args: Any, **kwargs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]], ] ], Command[CogT, P, T]]: ... @overload def command( self, name: str = ..., cls: Type[CommandT] = ..., *args: Any, **kwargs: Any, ) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], CommandT]: ... def command( self, name: str = MISSING, cls: Type[CommandT] = MISSING, *args: Any, **kwargs: Any, ) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], CommandT]: """A shortcut decorator that invokes :func:`.command` and adds it to the internal command list via :meth:`~.GroupMixin.add_command`. Returns -------- Callable[..., :class:`Command`] A decorator that converts the provided method into a Command, adds it to the bot, then returns it. """ def decorator(func: Callable[Concatenate[ContextT, P], Coro[Any]]) -> CommandT: kwargs.setdefault('parent', self) result = command(name=name, cls=cls, *args, **kwargs)(func) self.add_command(result) return result return decorator @overload def group( self, name: str = ..., cls: Type[Group[CogT, P, T]] = ..., *args: Any, **kwargs: Any, ) -> Callable[[ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]] ] ], Group[CogT, P, T]]: ... @overload def group( self, name: str = ..., cls: Type[GroupT] = ..., *args: Any, **kwargs: Any, ) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], GroupT]: ... def group( self, name: str = MISSING, cls: Type[GroupT] = MISSING, *args: Any, **kwargs: Any, ) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], GroupT]: """A shortcut decorator that invokes :func:`.group` and adds it to the internal command list via :meth:`~.GroupMixin.add_command`. Returns -------- Callable[..., :class:`Group`] A decorator that converts the provided method into a Group, adds it to the bot, then returns it. """ def decorator(func: Callable[Concatenate[ContextT, P], Coro[Any]]) -> GroupT: kwargs.setdefault('parent', self) result = group(name=name, cls=cls, *args, **kwargs)(func) self.add_command(result) return result return decorator class Group(GroupMixin[CogT], Command[CogT, P, T]): """A class that implements a grouping protocol for commands to be executed as subcommands. This class is a subclass of :class:`.Command` and thus all options valid in :class:`.Command` are valid in here as well. Attributes ----------- invoke_without_command: :class:`bool` Indicates if the group callback should begin parsing and invocation only if no subcommand was found. Useful for making it an error handling function to tell the user that no subcommand was found or to have different functionality in case no subcommand was found. If this is ``False``, then the group callback will always be invoked first. This means that the checks and the parsing dictated by its parameters will be executed. Defaults to ``False``. case_insensitive: :class:`bool` Indicates if the group's commands should be case insensitive. Defaults to ``False``. """ def __init__(self, *args: Any, **attrs: Any) -> None: self.invoke_without_command: bool = attrs.pop('invoke_without_command', False) super().__init__(*args, **attrs) def copy(self: GroupT) -> GroupT: """Creates a copy of this :class:`Group`. Returns -------- :class:`Group` A new instance of this group. """ ret = super().copy() for cmd in self.commands: ret.add_command(cmd.copy()) return ret # type: ignore async def invoke(self, ctx: Context) -> None: ctx.invoked_subcommand = None ctx.subcommand_passed = None early_invoke = not self.invoke_without_command if early_invoke: await self.prepare(ctx) view = ctx.view previous = view.index view.skip_ws() trigger = view.get_word() if trigger: ctx.subcommand_passed = trigger ctx.invoked_subcommand = self.all_commands.get(trigger, None) if early_invoke: injected = hooked_wrapped_callback(self, ctx, self.callback) await injected(*ctx.args, **ctx.kwargs) ctx.invoked_parents.append(ctx.invoked_with) # type: ignore if trigger and ctx.invoked_subcommand: ctx.invoked_with = trigger await ctx.invoked_subcommand.invoke(ctx) elif not early_invoke: # undo the trigger parsing view.index = previous view.previous = previous await super().invoke(ctx) async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None: ctx.invoked_subcommand = None early_invoke = not self.invoke_without_command if early_invoke: ctx.command = self await self._parse_arguments(ctx) if call_hooks: await self.call_before_hooks(ctx) view = ctx.view previous = view.index view.skip_ws() trigger = view.get_word() if trigger: ctx.subcommand_passed = trigger ctx.invoked_subcommand = self.all_commands.get(trigger, None) if early_invoke: try: await self.callback(*ctx.args, **ctx.kwargs) # type: ignore except: ctx.command_failed = True raise finally: if call_hooks: await self.call_after_hooks(ctx) ctx.invoked_parents.append(ctx.invoked_with) # type: ignore if trigger and ctx.invoked_subcommand: ctx.invoked_with = trigger await ctx.invoked_subcommand.reinvoke(ctx, call_hooks=call_hooks) elif not early_invoke: # undo the trigger parsing view.index = previous view.previous = previous await super().reinvoke(ctx, call_hooks=call_hooks) # Decorators @overload def command( name: str = ..., cls: Type[Command[CogT, P, T]] = ..., **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]], ] ] , Command[CogT, P, T]]: ... @overload def command( name: str = ..., cls: Type[CommandT] = ..., **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[Any]], Callable[Concatenate[ContextT, P], Coro[Any]], ] ] , CommandT]: ... def command( name: str = MISSING, cls: Type[CommandT] = MISSING, **attrs: Any ) -> Callable[ [ Union[ Callable[Concatenate[ContextT, P], Coro[Any]], Callable[Concatenate[CogT, ContextT, P], Coro[T]], ] ] , Union[Command[CogT, P, T], CommandT]]: """A decorator that transforms a function into a :class:`.Command` or if called with :func:`.group`, :class:`.Group`. By default the ``help`` attribute is received automatically from the docstring of the function and is cleaned up with the use of ``inspect.cleandoc``. If the docstring is ``bytes``, then it is decoded into :class:`str` using utf-8 encoding. All checks added using the :func:`.check` & co. decorators are added into the function. There is no way to supply your own checks through this decorator. Parameters ----------- name: :class:`str` The name to create the command with. By default this uses the function name unchanged. cls The class to construct with. By default this is :class:`.Command`. You usually do not change this. attrs Keyword arguments to pass into the construction of the class denoted by ``cls``. Raises ------- TypeError If the function is not a coroutine or is already a command. """ if cls is MISSING: cls = Command # type: ignore def decorator(func: Union[ Callable[Concatenate[ContextT, P], Coro[Any]], Callable[Concatenate[CogT, ContextT, P], Coro[Any]], ]) -> CommandT: if isinstance(func, Command): raise TypeError('Callback is already a command.') return cls(func, name=name, **attrs) return decorator @overload def group( name: str = ..., cls: Type[Group[CogT, P, T]] = ..., **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]], ] ] , Group[CogT, P, T]]: ... @overload def group( name: str = ..., cls: Type[GroupT] = ..., **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[Any]], Callable[Concatenate[ContextT, P], Coro[Any]], ] ] , GroupT]: ... def group( name: str = MISSING, cls: Type[GroupT] = MISSING, **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[ContextT, P], Coro[Any]], Callable[Concatenate[CogT, ContextT, P], Coro[T]], ] ] , Union[Group[CogT, P, T], GroupT]]: """A decorator that transforms a function into a :class:`.Group`. This is similar to the :func:`.command` decorator but the ``cls`` parameter is set to :class:`Group` by default. .. versionchanged:: 1.1 The ``cls`` parameter can now be passed. """ if cls is MISSING: cls = Group # type: ignore return command(name=name, cls=cls, **attrs) # type: ignore def check(predicate: Check) -> Callable[[T], T]: r"""A decorator that adds a check to the :class:`.Command` or its subclasses. These checks could be accessed via :attr:`.Command.checks`. These checks should be predicates that take in a single parameter taking a :class:`.Context`. If the check returns a ``False``\-like value then during invocation a :exc:`.CheckFailure` exception is raised and sent to the :func:`.on_command_error` event. If an exception should be thrown in the predicate then it should be a subclass of :exc:`.CommandError`. Any exception not subclassed from it will be propagated while those subclassed will be sent to :func:`.on_command_error`. A special attribute named ``predicate`` is bound to the value returned by this decorator to retrieve the predicate passed to the decorator. This allows the following introspection and chaining to be done: .. code-block:: python3 def owner_or_permissions(**perms): original = commands.has_permissions(**perms).predicate async def extended_check(ctx): if ctx.guild is None: return False return ctx.guild.owner_id == ctx.author.id or await original(ctx) return commands.check(extended_check) .. note:: The function returned by ``predicate`` is **always** a coroutine, even if the original function was not a coroutine. .. versionchanged:: 1.3 The ``predicate`` attribute was added. Examples --------- Creating a basic check to see if the command invoker is you. .. code-block:: python3 def check_if_it_is_me(ctx): return ctx.message.author.id == 85309593344815104 @bot.command() @commands.check(check_if_it_is_me) async def only_for_me(ctx): await ctx.send('I know you!') Transforming common checks into its own decorator: .. code-block:: python3 def is_me(): def predicate(ctx): return ctx.message.author.id == 85309593344815104 return commands.check(predicate) @bot.command() @is_me() async def only_me(ctx): await ctx.send('Only you!') Parameters ----------- predicate: Callable[[:class:`Context`], :class:`bool`] The predicate to check if the command should be invoked. """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func.checks.append(predicate) else: if not hasattr(func, '__commands_checks__'): func.__commands_checks__ = [] func.__commands_checks__.append(predicate) return func if inspect.iscoroutinefunction(predicate): decorator.predicate = predicate else: @functools.wraps(predicate) async def wrapper(ctx): return predicate(ctx) # type: ignore decorator.predicate = wrapper return decorator # type: ignore def check_any(*checks: Check) -> Callable[[T], T]: r"""A :func:`check` that is added that checks if any of the checks passed will pass, i.e. using logical OR. If all checks fail then :exc:`.CheckAnyFailure` is raised to signal the failure. It inherits from :exc:`.CheckFailure`. .. note:: The ``predicate`` attribute for this function **is** a coroutine. .. versionadded:: 1.3 Parameters ------------ \*checks: Callable[[:class:`Context`], :class:`bool`] An argument list of checks that have been decorated with the :func:`check` decorator. Raises ------- TypeError A check passed has not been decorated with the :func:`check` decorator. Examples --------- Creating a basic check to see if it's the bot owner or the server owner: .. code-block:: python3 def is_guild_owner(): def predicate(ctx): return ctx.guild is not None and ctx.guild.owner_id == ctx.author.id return commands.check(predicate) @bot.command() @commands.check_any(commands.is_owner(), is_guild_owner()) async def only_for_owners(ctx): await ctx.send('Hello mister owner!') """ unwrapped = [] for wrapped in checks: try: pred = wrapped.predicate except AttributeError: raise TypeError(f'{wrapped!r} must be wrapped by commands.check decorator') from None else: unwrapped.append(pred) async def predicate(ctx: Context) -> bool: errors = [] for func in unwrapped: try: value = await func(ctx) except CheckFailure as e: errors.append(e) else: if value: return True # if we're here, all checks failed raise CheckAnyFailure(unwrapped, errors) return check(predicate) def has_role(item: Union[int, str]) -> Callable[[T], T]: """A :func:`.check` that is added that checks if the member invoking the command has the role specified via the name or ID specified. If a string is specified, you must give the exact name of the role, including caps and spelling. If an integer is specified, you must give the exact snowflake ID of the role. If the message is invoked in a private message context then the check will return ``False``. This check raises one of two special exceptions, :exc:`.MissingRole` if the user is missing a role, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.MissingRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` Parameters ----------- item: Union[:class:`int`, :class:`str`] The name or ID of the role to check. """ def predicate(ctx: Context) -> bool: if ctx.guild is None: raise NoPrivateMessage() # ctx.guild is None doesn't narrow ctx.author to Member if isinstance(item, int): role = discord.utils.get(ctx.author.roles, id=item) # type: ignore else: role = discord.utils.get(ctx.author.roles, name=item) # type: ignore if role is None: raise MissingRole(item) return True return check(predicate) def has_any_role(*items: Union[int, str]) -> Callable[[T], T]: r"""A :func:`.check` that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return `True`. Similar to :func:`.has_role`\, the names or IDs passed in must be exact. This check raises one of two special exceptions, :exc:`.MissingAnyRole` if the user is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.MissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` Parameters ----------- items: List[Union[:class:`str`, :class:`int`]] An argument list of names or IDs to check that the member has roles wise. Example -------- .. code-block:: python3 @bot.command() @commands.has_any_role('Library Devs', 'Moderators', 492212595072434186) async def cool(ctx): await ctx.send('You are cool indeed') """ def predicate(ctx): if ctx.guild is None: raise NoPrivateMessage() # ctx.guild is None doesn't narrow ctx.author to Member getter = functools.partial(discord.utils.get, ctx.author.roles) # type: ignore if any(getter(id=item) is not None if isinstance(item, int) else getter(name=item) is not None for item in items): return True raise MissingAnyRole(list(items)) return check(predicate) def bot_has_role(item: int) -> Callable[[T], T]: """Similar to :func:`.has_role` except checks if the bot itself has the role. This check raises one of two special exceptions, :exc:`.BotMissingRole` if the bot is missing the role, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.BotMissingRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` """ def predicate(ctx): if ctx.guild is None: raise NoPrivateMessage() me = ctx.me if isinstance(item, int): role = discord.utils.get(me.roles, id=item) else: role = discord.utils.get(me.roles, name=item) if role is None: raise BotMissingRole(item) return True return check(predicate) def bot_has_any_role(*items: int) -> Callable[[T], T]: """Similar to :func:`.has_any_role` except checks if the bot itself has any of the roles listed. This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.BotMissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic checkfailure """ def predicate(ctx): if ctx.guild is None: raise NoPrivateMessage() me = ctx.me getter = functools.partial(discord.utils.get, me.roles) if any(getter(id=item) is not None if isinstance(item, int) else getter(name=item) is not None for item in items): return True raise BotMissingAnyRole(list(items)) return check(predicate) def has_permissions(**perms: bool) -> Callable[[T], T]: """A :func:`.check` that is added that checks if the member has all of the permissions necessary. Note that this check operates on the current channel permissions, not the guild wide permissions. The permissions passed in must be exactly like the properties shown under :class:`.discord.Permissions`. This check raises a special exception, :exc:`.MissingPermissions` that is inherited from :exc:`.CheckFailure`. Parameters ------------ perms An argument list of permissions to check for. Example --------- .. code-block:: python3 @bot.command() @commands.has_permissions(manage_messages=True) async def test(ctx): await ctx.send('You can manage messages.') """ invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) if invalid: raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") def predicate(ctx: Context) -> bool: ch = ctx.channel permissions = ch.permissions_for(ctx.author) # type: ignore missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] if not missing: return True raise MissingPermissions(missing) return check(predicate) def bot_has_permissions(**perms: bool) -> Callable[[T], T]: """Similar to :func:`.has_permissions` except checks if the bot itself has the permissions listed. This check raises a special exception, :exc:`.BotMissingPermissions` that is inherited from :exc:`.CheckFailure`. """ invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) if invalid: raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") def predicate(ctx: Context) -> bool: guild = ctx.guild me = guild.me if guild is not None else ctx.bot.user permissions = ctx.channel.permissions_for(me) # type: ignore missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] if not missing: return True raise BotMissingPermissions(missing) return check(predicate) def has_guild_permissions(**perms: bool) -> Callable[[T], T]: """Similar to :func:`.has_permissions`, but operates on guild wide permissions instead of the current channel permissions. If this check is called in a DM context, it will raise an exception, :exc:`.NoPrivateMessage`. .. versionadded:: 1.3 """ invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) if invalid: raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") def predicate(ctx: Context) -> bool: if not ctx.guild: raise NoPrivateMessage permissions = ctx.author.guild_permissions # type: ignore missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] if not missing: return True raise MissingPermissions(missing) return check(predicate) def bot_has_guild_permissions(**perms: bool) -> Callable[[T], T]: """Similar to :func:`.has_guild_permissions`, but checks the bot members guild permissions. .. versionadded:: 1.3 """ invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) if invalid: raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") def predicate(ctx: Context) -> bool: if not ctx.guild: raise NoPrivateMessage permissions = ctx.me.guild_permissions # type: ignore missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] if not missing: return True raise BotMissingPermissions(missing) return check(predicate) def dm_only() -> Callable[[T], T]: """A :func:`.check` that indicates this command must only be used in a DM context. Only private messages are allowed when using the command. This check raises a special exception, :exc:`.PrivateMessageOnly` that is inherited from :exc:`.CheckFailure`. .. versionadded:: 1.1 """ def predicate(ctx: Context) -> bool: if ctx.guild is not None: raise PrivateMessageOnly() return True return check(predicate) def guild_only() -> Callable[[T], T]: """A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.NoPrivateMessage` that is inherited from :exc:`.CheckFailure`. """ def predicate(ctx: Context) -> bool: if ctx.guild is None: raise NoPrivateMessage() return True return check(predicate) def is_owner() -> Callable[[T], T]: """A :func:`.check` that checks if the person invoking this command is the owner of the bot. This is powered by :meth:`.Bot.is_owner`. This check raises a special exception, :exc:`.NotOwner` that is derived from :exc:`.CheckFailure`. """ async def predicate(ctx: Context) -> bool: if not await ctx.bot.is_owner(ctx.author): raise NotOwner('You do not own this bot.') return True return check(predicate) def is_nsfw() -> Callable[[T], T]: """A :func:`.check` that checks if the channel is a NSFW channel. This check raises a special exception, :exc:`.NSFWChannelRequired` that is derived from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.NSFWChannelRequired` instead of generic :exc:`.CheckFailure`. DM channels will also now pass this check. """ def pred(ctx: Context) -> bool: ch = ctx.channel if ctx.guild is None or (isinstance(ch, (discord.TextChannel, discord.Thread)) and ch.is_nsfw()): return True raise NSFWChannelRequired(ch) # type: ignore return check(pred) def cooldown(rate: int, per: float, type: Union[BucketType, Callable[[Message], Any]] = BucketType.default) -> Callable[[T], T]: """A decorator that adds a cooldown to a :class:`.Command` A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of ``type`` which must be of enum type :class:`.BucketType`. If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in :func:`.on_command_error` and the local error handler. A command can only have a single cooldown. Parameters ------------ rate: :class:`int` The number of times a command can be used before triggering a cooldown. per: :class:`float` The amount of seconds to wait for a cooldown when it's been triggered. type: Union[:class:`.BucketType`, Callable[[:class:`.Message`], Any]] The type of cooldown to have. If callable, should return a key for the mapping. .. versionchanged:: 1.7 Callables are now supported for custom bucket types. """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func._buckets = CooldownMapping(Cooldown(rate, per), type) else: func.__commands_cooldown__ = CooldownMapping(Cooldown(rate, per), type) return func return decorator # type: ignore def dynamic_cooldown(cooldown: Union[BucketType, Callable[[Message], Any]], type: BucketType = BucketType.default) -> Callable[[T], T]: """A decorator that adds a dynamic cooldown to a :class:`.Command` This differs from :func:`.cooldown` in that it takes a function that accepts a single parameter of type :class:`.discord.Message` and must return a :class:`.Cooldown` or ``None``. If ``None`` is returned then that cooldown is effectively bypassed. A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of ``type`` which must be of enum type :class:`.BucketType`. If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in :func:`.on_command_error` and the local error handler. A command can only have a single cooldown. .. versionadded:: 2.0 Parameters ------------ cooldown: Callable[[:class:`.discord.Message`], Optional[:class:`.Cooldown`]] A function that takes a message and returns a cooldown that will apply to this invocation or ``None`` if the cooldown should be bypassed. type: :class:`.BucketType` The type of cooldown to have. """ if not callable(cooldown): raise TypeError("A callable must be provided") def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func._buckets = DynamicCooldownMapping(cooldown, type) else: func.__commands_cooldown__ = DynamicCooldownMapping(cooldown, type) return func return decorator # type: ignore def max_concurrency(number: int, per: BucketType = BucketType.default, *, wait: bool = False) -> Callable[[T], T]: """A decorator that adds a maximum concurrency to a :class:`.Command` or its subclasses. This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket -- only a set number of people can run the command. .. versionadded:: 1.3 Parameters ------------- number: :class:`int` The maximum number of invocations of this command that can be running at the same time. per: :class:`.BucketType` The bucket that this concurrency is based on, e.g. ``BucketType.guild`` would allow it to be used up to ``number`` times per guild. wait: :class:`bool` Whether the command should wait for the queue to be over. If this is set to ``False`` then instead of waiting until the command can run again, the command raises :exc:`.MaxConcurrencyReached` to its error handler. If this is set to ``True`` then the command waits until it can be executed. """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: value = MaxConcurrency(number, per=per, wait=wait) if isinstance(func, Command): func._max_concurrency = value else: func.__commands_max_concurrency__ = value return func return decorator # type: ignore def before_invoke(coro) -> Callable[[T], T]: """A decorator that registers a coroutine as a pre-invoke hook. This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog. .. versionadded:: 1.4 Example --------- .. code-block:: python3 async def record_usage(ctx): print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at) @bot.command() @commands.before_invoke(record_usage) async def who(ctx): # Output: <User> used who at <Time> await ctx.send('i am a bot') class What(commands.Cog): @commands.before_invoke(record_usage) @commands.command() async def when(self, ctx): # Output: <User> used when at <Time> await ctx.send(f'and i have existed since {ctx.bot.user.created_at}') @commands.command() async def where(self, ctx): # Output: <Nothing> await ctx.send('on Discord') @commands.command() async def why(self, ctx): # Output: <Nothing> await ctx.send('because someone made me') bot.add_cog(What()) """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func.before_invoke(coro) else: func.__before_invoke__ = coro return func return decorator # type: ignore def after_invoke(coro) -> Callable[[T], T]: """A decorator that registers a coroutine as a post-invoke hook. This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog. .. versionadded:: 1.4 """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func.after_invoke(coro) else: func.__after_invoke__ = coro return func return decorator # type: ignore
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ext/commands/core.py
core.py
from __future__ import annotations from typing import Any, Callable, Deque, Dict, Optional, Type, TypeVar, TYPE_CHECKING from discord.enums import Enum import time import asyncio from collections import deque from ...abc import PrivateChannel from .errors import MaxConcurrencyReached if TYPE_CHECKING: from ...message import Message __all__ = ( 'BucketType', 'Cooldown', 'CooldownMapping', 'DynamicCooldownMapping', 'MaxConcurrency', ) C = TypeVar('C', bound='CooldownMapping') MC = TypeVar('MC', bound='MaxConcurrency') class BucketType(Enum): default = 0 user = 1 guild = 2 channel = 3 member = 4 category = 5 role = 6 def get_key(self, msg: Message) -> Any: if self is BucketType.user: return msg.author.id elif self is BucketType.guild: return (msg.guild or msg.author).id elif self is BucketType.channel: return msg.channel.id elif self is BucketType.member: return ((msg.guild and msg.guild.id), msg.author.id) elif self is BucketType.category: return (msg.channel.category or msg.channel).id # type: ignore elif self is BucketType.role: # we return the channel id of a private-channel as there are only roles in guilds # and that yields the same result as for a guild with only the @everyone role # NOTE: PrivateChannel doesn't actually have an id attribute but we assume we are # recieving a DMChannel or GroupChannel which inherit from PrivateChannel and do return (msg.channel if isinstance(msg.channel, PrivateChannel) else msg.author.top_role).id # type: ignore def __call__(self, msg: Message) -> Any: return self.get_key(msg) class Cooldown: """Represents a cooldown for a command. Attributes ----------- rate: :class:`int` The total number of tokens available per :attr:`per` seconds. per: :class:`float` The length of the cooldown period in seconds. """ __slots__ = ('rate', 'per', '_window', '_tokens', '_last') def __init__(self, rate: float, per: float) -> None: self.rate: int = int(rate) self.per: float = float(per) self._window: float = 0.0 self._tokens: int = self.rate self._last: float = 0.0 def get_tokens(self, current: Optional[float] = None) -> int: """Returns the number of available tokens before rate limiting is applied. Parameters ------------ current: Optional[:class:`float`] The time in seconds since Unix epoch to calculate tokens at. If not supplied then :func:`time.time()` is used. Returns -------- :class:`int` The number of tokens available before the cooldown is to be applied. """ if not current: current = time.time() tokens = self._tokens if current > self._window + self.per: tokens = self.rate return tokens def get_retry_after(self, current: Optional[float] = None) -> float: """Returns the time in seconds until the cooldown will be reset. Parameters ------------- current: Optional[:class:`float`] The current time in seconds since Unix epoch. If not supplied, then :func:`time.time()` is used. Returns ------- :class:`float` The number of seconds to wait before this cooldown will be reset. """ current = current or time.time() tokens = self.get_tokens(current) if tokens == 0: return self.per - (current - self._window) return 0.0 def update_rate_limit(self, current: Optional[float] = None) -> Optional[float]: """Updates the cooldown rate limit. Parameters ------------- current: Optional[:class:`float`] The time in seconds since Unix epoch to update the rate limit at. If not supplied, then :func:`time.time()` is used. Returns ------- Optional[:class:`float`] The retry-after time in seconds if rate limited. """ current = current or time.time() self._last = current self._tokens = self.get_tokens(current) # first token used means that we start a new rate limit window if self._tokens == self.rate: self._window = current # check if we are rate limited if self._tokens == 0: return self.per - (current - self._window) # we're not so decrement our tokens self._tokens -= 1 def reset(self) -> None: """Reset the cooldown to its initial state.""" self._tokens = self.rate self._last = 0.0 def copy(self) -> Cooldown: """Creates a copy of this cooldown. Returns -------- :class:`Cooldown` A new instance of this cooldown. """ return Cooldown(self.rate, self.per) def __repr__(self) -> str: return f'<Cooldown rate: {self.rate} per: {self.per} window: {self._window} tokens: {self._tokens}>' class CooldownMapping: def __init__( self, original: Optional[Cooldown], type: Callable[[Message], Any], ) -> None: if not callable(type): raise TypeError('Cooldown type must be a BucketType or callable') self._cache: Dict[Any, Cooldown] = {} self._cooldown: Optional[Cooldown] = original self._type: Callable[[Message], Any] = type def copy(self) -> CooldownMapping: ret = CooldownMapping(self._cooldown, self._type) ret._cache = self._cache.copy() return ret @property def valid(self) -> bool: return self._cooldown is not None @property def type(self) -> Callable[[Message], Any]: return self._type @classmethod def from_cooldown(cls: Type[C], rate, per, type) -> C: return cls(Cooldown(rate, per), type) def _bucket_key(self, msg: Message) -> Any: return self._type(msg) def _verify_cache_integrity(self, current: Optional[float] = None) -> None: # we want to delete all cache objects that haven't been used # in a cooldown window. e.g. if we have a command that has a # cooldown of 60s and it has not been used in 60s then that key should be deleted current = current or time.time() dead_keys = [k for k, v in self._cache.items() if current > v._last + v.per] for k in dead_keys: del self._cache[k] def create_bucket(self, message: Message) -> Cooldown: return self._cooldown.copy() # type: ignore def get_bucket(self, message: Message, current: Optional[float] = None) -> Cooldown: if self._type is BucketType.default: return self._cooldown # type: ignore self._verify_cache_integrity(current) key = self._bucket_key(message) if key not in self._cache: bucket = self.create_bucket(message) if bucket is not None: self._cache[key] = bucket else: bucket = self._cache[key] return bucket def update_rate_limit(self, message: Message, current: Optional[float] = None) -> Optional[float]: bucket = self.get_bucket(message, current) return bucket.update_rate_limit(current) class DynamicCooldownMapping(CooldownMapping): def __init__( self, factory: Callable[[Message], Cooldown], type: Callable[[Message], Any] ) -> None: super().__init__(None, type) self._factory: Callable[[Message], Cooldown] = factory def copy(self) -> DynamicCooldownMapping: ret = DynamicCooldownMapping(self._factory, self._type) ret._cache = self._cache.copy() return ret @property def valid(self) -> bool: return True def create_bucket(self, message: Message) -> Cooldown: return self._factory(message) class _Semaphore: """This class is a version of a semaphore. If you're wondering why asyncio.Semaphore isn't being used, it's because it doesn't expose the internal value. This internal value is necessary because I need to support both `wait=True` and `wait=False`. An asyncio.Queue could have been used to do this as well -- but it is not as inefficient since internally that uses two queues and is a bit overkill for what is basically a counter. """ __slots__ = ('value', 'loop', '_waiters') def __init__(self, number: int) -> None: self.value: int = number self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() self._waiters: Deque[asyncio.Future] = deque() def __repr__(self) -> str: return f'<_Semaphore value={self.value} waiters={len(self._waiters)}>' def locked(self) -> bool: return self.value == 0 def is_active(self) -> bool: return len(self._waiters) > 0 def wake_up(self) -> None: while self._waiters: future = self._waiters.popleft() if not future.done(): future.set_result(None) return async def acquire(self, *, wait: bool = False) -> bool: if not wait and self.value <= 0: # signal that we're not acquiring return False while self.value <= 0: future = self.loop.create_future() self._waiters.append(future) try: await future except: future.cancel() if self.value > 0 and not future.cancelled(): self.wake_up() raise self.value -= 1 return True def release(self) -> None: self.value += 1 self.wake_up() class MaxConcurrency: __slots__ = ('number', 'per', 'wait', '_mapping') def __init__(self, number: int, *, per: BucketType, wait: bool) -> None: self._mapping: Dict[Any, _Semaphore] = {} self.per: BucketType = per self.number: int = number self.wait: bool = wait if number <= 0: raise ValueError('max_concurrency \'number\' cannot be less than 1') if not isinstance(per, BucketType): raise TypeError(f'max_concurrency \'per\' must be of type BucketType not {type(per)!r}') def copy(self: MC) -> MC: return self.__class__(self.number, per=self.per, wait=self.wait) def __repr__(self) -> str: return f'<MaxConcurrency per={self.per!r} number={self.number} wait={self.wait}>' def get_key(self, message: Message) -> Any: return self.per.get_key(message) async def acquire(self, message: Message) -> None: key = self.get_key(message) try: sem = self._mapping[key] except KeyError: self._mapping[key] = sem = _Semaphore(self.number) acquired = await sem.acquire(wait=self.wait) if not acquired: raise MaxConcurrencyReached(self.number, self.per) async def release(self, message: Message) -> None: # Technically there's no reason for this function to be async # But it might be more useful in the future key = self.get_key(message) try: sem = self._mapping[key] except KeyError: # ...? peculiar return else: sem.release() if sem.value >= self.number and not sem.is_active(): del self._mapping[key]
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ext/commands/cooldowns.py
cooldowns.py
from __future__ import annotations from typing import Optional, Any, TYPE_CHECKING, List, Callable, Type, Tuple, Union from discord.errors import ClientException, DiscordException if TYPE_CHECKING: from inspect import Parameter from .converter import Converter from .context import Context from .cooldowns import Cooldown, BucketType from .flags import Flag from discord.abc import GuildChannel from discord.threads import Thread from discord.types.snowflake import Snowflake, SnowflakeList __all__ = ( 'CommandError', 'MissingRequiredArgument', 'BadArgument', 'PrivateMessageOnly', 'NoPrivateMessage', 'CheckFailure', 'CheckAnyFailure', 'CommandNotFound', 'DisabledCommand', 'CommandInvokeError', 'TooManyArguments', 'UserInputError', 'CommandOnCooldown', 'MaxConcurrencyReached', 'NotOwner', 'MessageNotFound', 'ObjectNotFound', 'MemberNotFound', 'GuildNotFound', 'UserNotFound', 'ChannelNotFound', 'ThreadNotFound', 'ChannelNotReadable', 'BadColourArgument', 'BadColorArgument', 'RoleNotFound', 'BadInviteArgument', 'EmojiNotFound', 'GuildStickerNotFound', 'PartialEmojiConversionFailure', 'BadBoolArgument', 'MissingRole', 'BotMissingRole', 'MissingAnyRole', 'BotMissingAnyRole', 'MissingPermissions', 'BotMissingPermissions', 'NSFWChannelRequired', 'ConversionError', 'BadUnionArgument', 'BadLiteralArgument', 'ArgumentParsingError', 'UnexpectedQuoteError', 'InvalidEndOfQuotedStringError', 'ExpectedClosingQuoteError', 'ExtensionError', 'ExtensionAlreadyLoaded', 'ExtensionNotLoaded', 'NoEntryPointError', 'ExtensionFailed', 'ExtensionNotFound', 'CommandRegistrationError', 'FlagError', 'BadFlagArgument', 'MissingFlagArgument', 'TooManyFlags', 'MissingRequiredFlag', ) class CommandError(DiscordException): r"""The base exception type for all command related errors. This inherits from :exc:`discord.DiscordException`. This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from :class:`.Bot`\, :func:`.on_command_error`. """ def __init__(self, message: Optional[str] = None, *args: Any) -> None: if message is not None: # clean-up @everyone and @here mentions m = message.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere') super().__init__(m, *args) else: super().__init__(*args) class ConversionError(CommandError): """Exception raised when a Converter class raises non-CommandError. This inherits from :exc:`CommandError`. Attributes ---------- converter: :class:`discord.ext.commands.Converter` The converter that failed. original: :exc:`Exception` The original exception that was raised. You can also get this via the ``__cause__`` attribute. """ def __init__(self, converter: Converter, original: Exception) -> None: self.converter: Converter = converter self.original: Exception = original class UserInputError(CommandError): """The base exception type for errors that involve errors regarding user input. This inherits from :exc:`CommandError`. """ pass class CommandNotFound(CommandError): """Exception raised when a command is attempted to be invoked but no command under that name is found. This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked. This inherits from :exc:`CommandError`. """ pass class MissingRequiredArgument(UserInputError): """Exception raised when parsing a command and a parameter that is required is not encountered. This inherits from :exc:`UserInputError` Attributes ----------- param: :class:`inspect.Parameter` The argument that is missing. """ def __init__(self, param: Parameter) -> None: self.param: Parameter = param super().__init__(f'{param.name} is a required argument that is missing.') class TooManyArguments(UserInputError): """Exception raised when the command was passed too many arguments and its :attr:`.Command.ignore_extra` attribute was not set to ``True``. This inherits from :exc:`UserInputError` """ pass class BadArgument(UserInputError): """Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command. This inherits from :exc:`UserInputError` """ pass class CheckFailure(CommandError): """Exception raised when the predicates in :attr:`.Command.checks` have failed. This inherits from :exc:`CommandError` """ pass class CheckAnyFailure(CheckFailure): """Exception raised when all predicates in :func:`check_any` fail. This inherits from :exc:`CheckFailure`. .. versionadded:: 1.3 Attributes ------------ errors: List[:class:`CheckFailure`] A list of errors that were caught during execution. checks: List[Callable[[:class:`Context`], :class:`bool`]] A list of check predicates that failed. """ def __init__(self, checks: List[CheckFailure], errors: List[Callable[[Context], bool]]) -> None: self.checks: List[CheckFailure] = checks self.errors: List[Callable[[Context], bool]] = errors super().__init__('You do not have permission to run this command.') class PrivateMessageOnly(CheckFailure): """Exception raised when an operation does not work outside of private message contexts. This inherits from :exc:`CheckFailure` """ def __init__(self, message: Optional[str] = None) -> None: super().__init__(message or 'This command can only be used in private messages.') class NoPrivateMessage(CheckFailure): """Exception raised when an operation does not work in private message contexts. This inherits from :exc:`CheckFailure` """ def __init__(self, message: Optional[str] = None) -> None: super().__init__(message or 'This command cannot be used in private messages.') class NotOwner(CheckFailure): """Exception raised when the message author is not the owner of the bot. This inherits from :exc:`CheckFailure` """ pass class ObjectNotFound(BadArgument): """Exception raised when the argument provided did not match the format of an ID or a mention. This inherits from :exc:`BadArgument` .. versionadded:: 2.0 Attributes ----------- argument: :class:`str` The argument supplied by the caller that was not matched """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'{argument!r} does not follow a valid ID or mention format.') class MemberNotFound(BadArgument): """Exception raised when the member provided was not found in the bot's cache. This inherits from :exc:`BadArgument` .. versionadded:: 1.5 Attributes ----------- argument: :class:`str` The member supplied by the caller that was not found """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'Member "{argument}" not found.') class GuildNotFound(BadArgument): """Exception raised when the guild provided was not found in the bot's cache. This inherits from :exc:`BadArgument` .. versionadded:: 1.7 Attributes ----------- argument: :class:`str` The guild supplied by the called that was not found """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'Guild "{argument}" not found.') class UserNotFound(BadArgument): """Exception raised when the user provided was not found in the bot's cache. This inherits from :exc:`BadArgument` .. versionadded:: 1.5 Attributes ----------- argument: :class:`str` The user supplied by the caller that was not found """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'User "{argument}" not found.') class MessageNotFound(BadArgument): """Exception raised when the message provided was not found in the channel. This inherits from :exc:`BadArgument` .. versionadded:: 1.5 Attributes ----------- argument: :class:`str` The message supplied by the caller that was not found """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'Message "{argument}" not found.') class ChannelNotReadable(BadArgument): """Exception raised when the bot does not have permission to read messages in the channel. This inherits from :exc:`BadArgument` .. versionadded:: 1.5 Attributes ----------- argument: Union[:class:`.abc.GuildChannel`, :class:`.Thread`] The channel supplied by the caller that was not readable """ def __init__(self, argument: Union[GuildChannel, Thread]) -> None: self.argument: Union[GuildChannel, Thread] = argument super().__init__(f"Can't read messages in {argument.mention}.") class ChannelNotFound(BadArgument): """Exception raised when the bot can not find the channel. This inherits from :exc:`BadArgument` .. versionadded:: 1.5 Attributes ----------- argument: :class:`str` The channel supplied by the caller that was not found """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'Channel "{argument}" not found.') class ThreadNotFound(BadArgument): """Exception raised when the bot can not find the thread. This inherits from :exc:`BadArgument` .. versionadded:: 2.0 Attributes ----------- argument: :class:`str` The thread supplied by the caller that was not found """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'Thread "{argument}" not found.') class BadColourArgument(BadArgument): """Exception raised when the colour is not valid. This inherits from :exc:`BadArgument` .. versionadded:: 1.5 Attributes ----------- argument: :class:`str` The colour supplied by the caller that was not valid """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'Colour "{argument}" is invalid.') BadColorArgument = BadColourArgument class RoleNotFound(BadArgument): """Exception raised when the bot can not find the role. This inherits from :exc:`BadArgument` .. versionadded:: 1.5 Attributes ----------- argument: :class:`str` The role supplied by the caller that was not found """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'Role "{argument}" not found.') class BadInviteArgument(BadArgument): """Exception raised when the invite is invalid or expired. This inherits from :exc:`BadArgument` .. versionadded:: 1.5 """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'Invite "{argument}" is invalid or expired.') class EmojiNotFound(BadArgument): """Exception raised when the bot can not find the emoji. This inherits from :exc:`BadArgument` .. versionadded:: 1.5 Attributes ----------- argument: :class:`str` The emoji supplied by the caller that was not found """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'Emoji "{argument}" not found.') class PartialEmojiConversionFailure(BadArgument): """Exception raised when the emoji provided does not match the correct format. This inherits from :exc:`BadArgument` .. versionadded:: 1.5 Attributes ----------- argument: :class:`str` The emoji supplied by the caller that did not match the regex """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'Couldn\'t convert "{argument}" to PartialEmoji.') class GuildStickerNotFound(BadArgument): """Exception raised when the bot can not find the sticker. This inherits from :exc:`BadArgument` .. versionadded:: 2.0 Attributes ----------- argument: :class:`str` The sticker supplied by the caller that was not found """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'Sticker "{argument}" not found.') class BadBoolArgument(BadArgument): """Exception raised when a boolean argument was not convertable. This inherits from :exc:`BadArgument` .. versionadded:: 1.5 Attributes ----------- argument: :class:`str` The boolean argument supplied by the caller that is not in the predefined list """ def __init__(self, argument: str) -> None: self.argument: str = argument super().__init__(f'{argument} is not a recognised boolean option') class DisabledCommand(CommandError): """Exception raised when the command being invoked is disabled. This inherits from :exc:`CommandError` """ pass class CommandInvokeError(CommandError): """Exception raised when the command being invoked raised an exception. This inherits from :exc:`CommandError` Attributes ----------- original: :exc:`Exception` The original exception that was raised. You can also get this via the ``__cause__`` attribute. """ def __init__(self, e: Exception) -> None: self.original: Exception = e super().__init__(f'Command raised an exception: {e.__class__.__name__}: {e}') class CommandOnCooldown(CommandError): """Exception raised when the command being invoked is on cooldown. This inherits from :exc:`CommandError` Attributes ----------- cooldown: :class:`.Cooldown` A class with attributes ``rate`` and ``per`` similar to the :func:`.cooldown` decorator. type: :class:`BucketType` The type associated with the cooldown. retry_after: :class:`float` The amount of seconds to wait before you can retry again. """ def __init__(self, cooldown: Cooldown, retry_after: float, type: BucketType) -> None: self.cooldown: Cooldown = cooldown self.retry_after: float = retry_after self.type: BucketType = type super().__init__(f'You are on cooldown. Try again in {retry_after:.2f}s') class MaxConcurrencyReached(CommandError): """Exception raised when the command being invoked has reached its maximum concurrency. This inherits from :exc:`CommandError`. Attributes ------------ number: :class:`int` The maximum number of concurrent invokers allowed. per: :class:`.BucketType` The bucket type passed to the :func:`.max_concurrency` decorator. """ def __init__(self, number: int, per: BucketType) -> None: self.number: int = number self.per: BucketType = per name = per.name suffix = 'per %s' % name if per.name != 'default' else 'globally' plural = '%s times %s' if number > 1 else '%s time %s' fmt = plural % (number, suffix) super().__init__(f'Too many people are using this command. It can only be used {fmt} concurrently.') class MissingRole(CheckFailure): """Exception raised when the command invoker lacks a role to run a command. This inherits from :exc:`CheckFailure` .. versionadded:: 1.1 Attributes ----------- missing_role: Union[:class:`str`, :class:`int`] The required role that is missing. This is the parameter passed to :func:`~.commands.has_role`. """ def __init__(self, missing_role: Snowflake) -> None: self.missing_role: Snowflake = missing_role message = f'Role {missing_role!r} is required to run this command.' super().__init__(message) class BotMissingRole(CheckFailure): """Exception raised when the bot's member lacks a role to run a command. This inherits from :exc:`CheckFailure` .. versionadded:: 1.1 Attributes ----------- missing_role: Union[:class:`str`, :class:`int`] The required role that is missing. This is the parameter passed to :func:`~.commands.has_role`. """ def __init__(self, missing_role: Snowflake) -> None: self.missing_role: Snowflake = missing_role message = f'Bot requires the role {missing_role!r} to run this command' super().__init__(message) class MissingAnyRole(CheckFailure): """Exception raised when the command invoker lacks any of the roles specified to run a command. This inherits from :exc:`CheckFailure` .. versionadded:: 1.1 Attributes ----------- missing_roles: List[Union[:class:`str`, :class:`int`]] The roles that the invoker is missing. These are the parameters passed to :func:`~.commands.has_any_role`. """ def __init__(self, missing_roles: SnowflakeList) -> None: self.missing_roles: SnowflakeList = missing_roles missing = [f"'{role}'" for role in missing_roles] if len(missing) > 2: fmt = '{}, or {}'.format(", ".join(missing[:-1]), missing[-1]) else: fmt = ' or '.join(missing) message = f"You are missing at least one of the required roles: {fmt}" super().__init__(message) class BotMissingAnyRole(CheckFailure): """Exception raised when the bot's member lacks any of the roles specified to run a command. This inherits from :exc:`CheckFailure` .. versionadded:: 1.1 Attributes ----------- missing_roles: List[Union[:class:`str`, :class:`int`]] The roles that the bot's member is missing. These are the parameters passed to :func:`~.commands.has_any_role`. """ def __init__(self, missing_roles: SnowflakeList) -> None: self.missing_roles: SnowflakeList = missing_roles missing = [f"'{role}'" for role in missing_roles] if len(missing) > 2: fmt = '{}, or {}'.format(", ".join(missing[:-1]), missing[-1]) else: fmt = ' or '.join(missing) message = f"Bot is missing at least one of the required roles: {fmt}" super().__init__(message) class NSFWChannelRequired(CheckFailure): """Exception raised when a channel does not have the required NSFW setting. This inherits from :exc:`CheckFailure`. .. versionadded:: 1.1 Parameters ----------- channel: Union[:class:`.abc.GuildChannel`, :class:`.Thread`] The channel that does not have NSFW enabled. """ def __init__(self, channel: Union[GuildChannel, Thread]) -> None: self.channel: Union[GuildChannel, Thread] = channel super().__init__(f"Channel '{channel}' needs to be NSFW for this command to work.") class MissingPermissions(CheckFailure): """Exception raised when the command invoker lacks permissions to run a command. This inherits from :exc:`CheckFailure` Attributes ----------- missing_permissions: List[:class:`str`] The required permissions that are missing. """ def __init__(self, missing_permissions: List[str], *args: Any) -> None: self.missing_permissions: List[str] = missing_permissions missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in missing_permissions] if len(missing) > 2: fmt = '{}, and {}'.format(", ".join(missing[:-1]), missing[-1]) else: fmt = ' and '.join(missing) message = f'You are missing {fmt} permission(s) to run this command.' super().__init__(message, *args) class BotMissingPermissions(CheckFailure): """Exception raised when the bot's member lacks permissions to run a command. This inherits from :exc:`CheckFailure` Attributes ----------- missing_permissions: List[:class:`str`] The required permissions that are missing. """ def __init__(self, missing_permissions: List[str], *args: Any) -> None: self.missing_permissions: List[str] = missing_permissions missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in missing_permissions] if len(missing) > 2: fmt = '{}, and {}'.format(", ".join(missing[:-1]), missing[-1]) else: fmt = ' and '.join(missing) message = f'Bot requires {fmt} permission(s) to run this command.' super().__init__(message, *args) class BadUnionArgument(UserInputError): """Exception raised when a :data:`typing.Union` converter fails for all its associated types. This inherits from :exc:`UserInputError` Attributes ----------- param: :class:`inspect.Parameter` The parameter that failed being converted. converters: Tuple[Type, ``...``] A tuple of converters attempted in conversion, in order of failure. errors: List[:class:`CommandError`] A list of errors that were caught from failing the conversion. """ def __init__(self, param: Parameter, converters: Tuple[Type, ...], errors: List[CommandError]) -> None: self.param: Parameter = param self.converters: Tuple[Type, ...] = converters self.errors: List[CommandError] = errors def _get_name(x): try: return x.__name__ except AttributeError: if hasattr(x, '__origin__'): return repr(x) return x.__class__.__name__ to_string = [_get_name(x) for x in converters] if len(to_string) > 2: fmt = '{}, or {}'.format(', '.join(to_string[:-1]), to_string[-1]) else: fmt = ' or '.join(to_string) super().__init__(f'Could not convert "{param.name}" into {fmt}.') class BadLiteralArgument(UserInputError): """Exception raised when a :data:`typing.Literal` converter fails for all its associated values. This inherits from :exc:`UserInputError` .. versionadded:: 2.0 Attributes ----------- param: :class:`inspect.Parameter` The parameter that failed being converted. literals: Tuple[Any, ``...``] A tuple of values compared against in conversion, in order of failure. errors: List[:class:`CommandError`] A list of errors that were caught from failing the conversion. """ def __init__(self, param: Parameter, literals: Tuple[Any, ...], errors: List[CommandError]) -> None: self.param: Parameter = param self.literals: Tuple[Any, ...] = literals self.errors: List[CommandError] = errors to_string = [repr(l) for l in literals] if len(to_string) > 2: fmt = '{}, or {}'.format(', '.join(to_string[:-1]), to_string[-1]) else: fmt = ' or '.join(to_string) super().__init__(f'Could not convert "{param.name}" into the literal {fmt}.') class ArgumentParsingError(UserInputError): """An exception raised when the parser fails to parse a user's input. This inherits from :exc:`UserInputError`. There are child classes that implement more granular parsing errors for i18n purposes. """ pass class UnexpectedQuoteError(ArgumentParsingError): """An exception raised when the parser encounters a quote mark inside a non-quoted string. This inherits from :exc:`ArgumentParsingError`. Attributes ------------ quote: :class:`str` The quote mark that was found inside the non-quoted string. """ def __init__(self, quote: str) -> None: self.quote: str = quote super().__init__(f'Unexpected quote mark, {quote!r}, in non-quoted string') class InvalidEndOfQuotedStringError(ArgumentParsingError): """An exception raised when a space is expected after the closing quote in a string but a different character is found. This inherits from :exc:`ArgumentParsingError`. Attributes ----------- char: :class:`str` The character found instead of the expected string. """ def __init__(self, char: str) -> None: self.char: str = char super().__init__(f'Expected space after closing quotation but received {char!r}') class ExpectedClosingQuoteError(ArgumentParsingError): """An exception raised when a quote character is expected but not found. This inherits from :exc:`ArgumentParsingError`. Attributes ----------- close_quote: :class:`str` The quote character expected. """ def __init__(self, close_quote: str) -> None: self.close_quote: str = close_quote super().__init__(f'Expected closing {close_quote}.') class ExtensionError(DiscordException): """Base exception for extension related errors. This inherits from :exc:`~discord.DiscordException`. Attributes ------------ name: :class:`str` The extension that had an error. """ def __init__(self, message: Optional[str] = None, *args: Any, name: str) -> None: self.name: str = name message = message or f'Extension {name!r} had an error.' # clean-up @everyone and @here mentions m = message.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere') super().__init__(m, *args) class ExtensionAlreadyLoaded(ExtensionError): """An exception raised when an extension has already been loaded. This inherits from :exc:`ExtensionError` """ def __init__(self, name: str) -> None: super().__init__(f'Extension {name!r} is already loaded.', name=name) class ExtensionNotLoaded(ExtensionError): """An exception raised when an extension was not loaded. This inherits from :exc:`ExtensionError` """ def __init__(self, name: str) -> None: super().__init__(f'Extension {name!r} has not been loaded.', name=name) class NoEntryPointError(ExtensionError): """An exception raised when an extension does not have a ``setup`` entry point function. This inherits from :exc:`ExtensionError` """ def __init__(self, name: str) -> None: super().__init__(f"Extension {name!r} has no 'setup' function.", name=name) class ExtensionFailed(ExtensionError): """An exception raised when an extension failed to load during execution of the module or ``setup`` entry point. This inherits from :exc:`ExtensionError` Attributes ----------- name: :class:`str` The extension that had the error. original: :exc:`Exception` The original exception that was raised. You can also get this via the ``__cause__`` attribute. """ def __init__(self, name: str, original: Exception) -> None: self.original: Exception = original msg = f'Extension {name!r} raised an error: {original.__class__.__name__}: {original}' super().__init__(msg, name=name) class ExtensionNotFound(ExtensionError): """An exception raised when an extension is not found. This inherits from :exc:`ExtensionError` .. versionchanged:: 1.3 Made the ``original`` attribute always None. Attributes ----------- name: :class:`str` The extension that had the error. """ def __init__(self, name: str) -> None: msg = f'Extension {name!r} could not be loaded.' super().__init__(msg, name=name) class CommandRegistrationError(ClientException): """An exception raised when the command can't be added because the name is already taken by a different command. This inherits from :exc:`discord.ClientException` .. versionadded:: 1.4 Attributes ---------- name: :class:`str` The command name that had the error. alias_conflict: :class:`bool` Whether the name that conflicts is an alias of the command we try to add. """ def __init__(self, name: str, *, alias_conflict: bool = False) -> None: self.name: str = name self.alias_conflict: bool = alias_conflict type_ = 'alias' if alias_conflict else 'command' super().__init__(f'The {type_} {name} is already an existing command or alias.') class FlagError(BadArgument): """The base exception type for all flag parsing related errors. This inherits from :exc:`BadArgument`. .. versionadded:: 2.0 """ pass class TooManyFlags(FlagError): """An exception raised when a flag has received too many values. This inherits from :exc:`FlagError`. .. versionadded:: 2.0 Attributes ------------ flag: :class:`~discord.ext.commands.Flag` The flag that received too many values. values: List[:class:`str`] The values that were passed. """ def __init__(self, flag: Flag, values: List[str]) -> None: self.flag: Flag = flag self.values: List[str] = values super().__init__(f'Too many flag values, expected {flag.max_args} but received {len(values)}.') class BadFlagArgument(FlagError): """An exception raised when a flag failed to convert a value. This inherits from :exc:`FlagError` .. versionadded:: 2.0 Attributes ----------- flag: :class:`~discord.ext.commands.Flag` The flag that failed to convert. """ def __init__(self, flag: Flag) -> None: self.flag: Flag = flag try: name = flag.annotation.__name__ except AttributeError: name = flag.annotation.__class__.__name__ super().__init__(f'Could not convert to {name!r} for flag {flag.name!r}') class MissingRequiredFlag(FlagError): """An exception raised when a required flag was not given. This inherits from :exc:`FlagError` .. versionadded:: 2.0 Attributes ----------- flag: :class:`~discord.ext.commands.Flag` The required flag that was not found. """ def __init__(self, flag: Flag) -> None: self.flag: Flag = flag super().__init__(f'Flag {flag.name!r} is required and missing') class MissingFlagArgument(FlagError): """An exception raised when a flag did not get a value. This inherits from :exc:`FlagError` .. versionadded:: 2.0 Attributes ----------- flag: :class:`~discord.ext.commands.Flag` The flag that did not get a value. """ def __init__(self, flag: Flag) -> None: self.flag: Flag = flag super().__init__(f'Flag {flag.name!r} does not have an argument')
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ext/commands/errors.py
errors.py
from __future__ import annotations from .errors import ( BadFlagArgument, CommandError, MissingFlagArgument, TooManyFlags, MissingRequiredFlag, ) from discord.utils import resolve_annotation from .view import StringView from .converter import run_converters from discord.utils import maybe_coroutine, MISSING from dataclasses import dataclass, field from typing import ( Dict, Iterator, Literal, Optional, Pattern, Set, TYPE_CHECKING, Tuple, List, Any, Type, TypeVar, Union, ) import inspect import sys import re __all__ = ( 'Flag', 'flag', 'FlagConverter', ) if TYPE_CHECKING: from .context import Context @dataclass class Flag: """Represents a flag parameter for :class:`FlagConverter`. The :func:`~discord.ext.commands.flag` function helps create these flag objects, but it is not necessary to do so. These cannot be constructed manually. Attributes ------------ name: :class:`str` The name of the flag. aliases: List[:class:`str`] The aliases of the flag name. attribute: :class:`str` The attribute in the class that corresponds to this flag. default: Any The default value of the flag, if available. annotation: Any The underlying evaluated annotation of the flag. max_args: :class:`int` The maximum number of arguments the flag can accept. A negative value indicates an unlimited amount of arguments. override: :class:`bool` Whether multiple given values overrides the previous value. """ name: str = MISSING aliases: List[str] = field(default_factory=list) attribute: str = MISSING annotation: Any = MISSING default: Any = MISSING max_args: int = MISSING override: bool = MISSING cast_to_dict: bool = False @property def required(self) -> bool: """:class:`bool`: Whether the flag is required. A required flag has no default value. """ return self.default is MISSING def flag( *, name: str = MISSING, aliases: List[str] = MISSING, default: Any = MISSING, max_args: int = MISSING, override: bool = MISSING, ) -> Any: """Override default functionality and parameters of the underlying :class:`FlagConverter` class attributes. Parameters ------------ name: :class:`str` The flag name. If not given, defaults to the attribute name. aliases: List[:class:`str`] Aliases to the flag name. If not given no aliases are set. default: Any The default parameter. This could be either a value or a callable that takes :class:`Context` as its sole parameter. If not given then it defaults to the default value given to the attribute. max_args: :class:`int` The maximum number of arguments the flag can accept. A negative value indicates an unlimited amount of arguments. The default value depends on the annotation given. override: :class:`bool` Whether multiple given values overrides the previous value. The default value depends on the annotation given. """ return Flag(name=name, aliases=aliases, default=default, max_args=max_args, override=override) def validate_flag_name(name: str, forbidden: Set[str]): if not name: raise ValueError('flag names should not be empty') for ch in name: if ch.isspace(): raise ValueError(f'flag name {name!r} cannot have spaces') if ch == '\\': raise ValueError(f'flag name {name!r} cannot have backslashes') if ch in forbidden: raise ValueError(f'flag name {name!r} cannot have any of {forbidden!r} within them') def get_flags(namespace: Dict[str, Any], globals: Dict[str, Any], locals: Dict[str, Any]) -> Dict[str, Flag]: annotations = namespace.get('__annotations__', {}) case_insensitive = namespace['__commands_flag_case_insensitive__'] flags: Dict[str, Flag] = {} cache: Dict[str, Any] = {} names: Set[str] = set() for name, annotation in annotations.items(): flag = namespace.pop(name, MISSING) if isinstance(flag, Flag): flag.annotation = annotation else: flag = Flag(name=name, annotation=annotation, default=flag) flag.attribute = name if flag.name is MISSING: flag.name = name annotation = flag.annotation = resolve_annotation(flag.annotation, globals, locals, cache) if flag.default is MISSING and hasattr(annotation, '__commands_is_flag__') and annotation._can_be_constructible(): flag.default = annotation._construct_default if flag.aliases is MISSING: flag.aliases = [] # Add sensible defaults based off of the type annotation # <type> -> (max_args=1) # List[str] -> (max_args=-1) # Tuple[int, ...] -> (max_args=1) # Dict[K, V] -> (max_args=-1, override=True) # Union[str, int] -> (max_args=1) # Optional[str] -> (default=None, max_args=1) try: origin = annotation.__origin__ except AttributeError: # A regular type hint if flag.max_args is MISSING: flag.max_args = 1 else: if origin is Union: # typing.Union if flag.max_args is MISSING: flag.max_args = 1 if annotation.__args__[-1] is type(None) and flag.default is MISSING: # typing.Optional flag.default = None elif origin is tuple: # typing.Tuple # tuple parsing is e.g. `flag: peter 20` # for Tuple[str, int] would give you flag: ('peter', 20) if flag.max_args is MISSING: flag.max_args = 1 elif origin is list: # typing.List if flag.max_args is MISSING: flag.max_args = -1 elif origin is dict: # typing.Dict[K, V] # Equivalent to: # typing.List[typing.Tuple[K, V]] flag.cast_to_dict = True if flag.max_args is MISSING: flag.max_args = -1 if flag.override is MISSING: flag.override = True elif origin is Literal: if flag.max_args is MISSING: flag.max_args = 1 else: raise TypeError(f'Unsupported typing annotation {annotation!r} for {flag.name!r} flag') if flag.override is MISSING: flag.override = False # Validate flag names are unique name = flag.name.casefold() if case_insensitive else flag.name if name in names: raise TypeError(f'{flag.name!r} flag conflicts with previous flag or alias.') else: names.add(name) for alias in flag.aliases: # Validate alias is unique alias = alias.casefold() if case_insensitive else alias if alias in names: raise TypeError(f'{flag.name!r} flag alias {alias!r} conflicts with previous flag or alias.') else: names.add(alias) flags[flag.name] = flag return flags class FlagsMeta(type): if TYPE_CHECKING: __commands_is_flag__: bool __commands_flags__: Dict[str, Flag] __commands_flag_aliases__: Dict[str, str] __commands_flag_regex__: Pattern[str] __commands_flag_case_insensitive__: bool __commands_flag_delimiter__: str __commands_flag_prefix__: str def __new__( cls: Type[type], name: str, bases: Tuple[type, ...], attrs: Dict[str, Any], *, case_insensitive: bool = MISSING, delimiter: str = MISSING, prefix: str = MISSING, ): attrs['__commands_is_flag__'] = True try: global_ns = sys.modules[attrs['__module__']].__dict__ except KeyError: global_ns = {} frame = inspect.currentframe() try: if frame is None: local_ns = {} else: if frame.f_back is None: local_ns = frame.f_locals else: local_ns = frame.f_back.f_locals finally: del frame flags: Dict[str, Flag] = {} aliases: Dict[str, str] = {} for base in reversed(bases): if base.__dict__.get('__commands_is_flag__', False): flags.update(base.__dict__['__commands_flags__']) aliases.update(base.__dict__['__commands_flag_aliases__']) if case_insensitive is MISSING: attrs['__commands_flag_case_insensitive__'] = base.__dict__['__commands_flag_case_insensitive__'] if delimiter is MISSING: attrs['__commands_flag_delimiter__'] = base.__dict__['__commands_flag_delimiter__'] if prefix is MISSING: attrs['__commands_flag_prefix__'] = base.__dict__['__commands_flag_prefix__'] if case_insensitive is not MISSING: attrs['__commands_flag_case_insensitive__'] = case_insensitive if delimiter is not MISSING: attrs['__commands_flag_delimiter__'] = delimiter if prefix is not MISSING: attrs['__commands_flag_prefix__'] = prefix case_insensitive = attrs.setdefault('__commands_flag_case_insensitive__', False) delimiter = attrs.setdefault('__commands_flag_delimiter__', ':') prefix = attrs.setdefault('__commands_flag_prefix__', '') for flag_name, flag in get_flags(attrs, global_ns, local_ns).items(): flags[flag_name] = flag aliases.update({alias_name: flag_name for alias_name in flag.aliases}) forbidden = set(delimiter).union(prefix) for flag_name in flags: validate_flag_name(flag_name, forbidden) for alias_name in aliases: validate_flag_name(alias_name, forbidden) regex_flags = 0 if case_insensitive: flags = {key.casefold(): value for key, value in flags.items()} aliases = {key.casefold(): value.casefold() for key, value in aliases.items()} regex_flags = re.IGNORECASE keys = list(re.escape(k) for k in flags) keys.extend(re.escape(a) for a in aliases) keys = sorted(keys, key=lambda t: len(t), reverse=True) joined = '|'.join(keys) pattern = re.compile(f'(({re.escape(prefix)})(?P<flag>{joined}){re.escape(delimiter)})', regex_flags) attrs['__commands_flag_regex__'] = pattern attrs['__commands_flags__'] = flags attrs['__commands_flag_aliases__'] = aliases return type.__new__(cls, name, bases, attrs) async def tuple_convert_all(ctx: Context, argument: str, flag: Flag, converter: Any) -> Tuple[Any, ...]: view = StringView(argument) results = [] param: inspect.Parameter = ctx.current_parameter # type: ignore while not view.eof: view.skip_ws() if view.eof: break word = view.get_quoted_word() if word is None: break try: converted = await run_converters(ctx, converter, word, param) except CommandError: raise except Exception as e: raise BadFlagArgument(flag) from e else: results.append(converted) return tuple(results) async def tuple_convert_flag(ctx: Context, argument: str, flag: Flag, converters: Any) -> Tuple[Any, ...]: view = StringView(argument) results = [] param: inspect.Parameter = ctx.current_parameter # type: ignore for converter in converters: view.skip_ws() if view.eof: break word = view.get_quoted_word() if word is None: break try: converted = await run_converters(ctx, converter, word, param) except CommandError: raise except Exception as e: raise BadFlagArgument(flag) from e else: results.append(converted) if len(results) != len(converters): raise BadFlagArgument(flag) return tuple(results) async def convert_flag(ctx, argument: str, flag: Flag, annotation: Any = None) -> Any: param: inspect.Parameter = ctx.current_parameter # type: ignore annotation = annotation or flag.annotation try: origin = annotation.__origin__ except AttributeError: pass else: if origin is tuple: if annotation.__args__[-1] is Ellipsis: return await tuple_convert_all(ctx, argument, flag, annotation.__args__[0]) else: return await tuple_convert_flag(ctx, argument, flag, annotation.__args__) elif origin is list: # typing.List[x] annotation = annotation.__args__[0] return await convert_flag(ctx, argument, flag, annotation) elif origin is Union and annotation.__args__[-1] is type(None): # typing.Optional[x] annotation = Union[annotation.__args__[:-1]] return await run_converters(ctx, annotation, argument, param) elif origin is dict: # typing.Dict[K, V] -> typing.Tuple[K, V] return await tuple_convert_flag(ctx, argument, flag, annotation.__args__) try: return await run_converters(ctx, annotation, argument, param) except CommandError: raise except Exception as e: raise BadFlagArgument(flag) from e F = TypeVar('F', bound='FlagConverter') class FlagConverter(metaclass=FlagsMeta): """A converter that allows for a user-friendly flag syntax. The flags are defined using :pep:`526` type annotations similar to the :mod:`dataclasses` Python module. For more information on how this converter works, check the appropriate :ref:`documentation <ext_commands_flag_converter>`. .. container:: operations .. describe:: iter(x) Returns an iterator of ``(flag_name, flag_value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown. .. versionadded:: 2.0 Parameters ----------- case_insensitive: :class:`bool` A class parameter to toggle case insensitivity of the flag parsing. If ``True`` then flags are parsed in a case insensitive manner. Defaults to ``False``. prefix: :class:`str` The prefix that all flags must be prefixed with. By default there is no prefix. delimiter: :class:`str` The delimiter that separates a flag's argument from the flag's name. By default this is ``:``. """ @classmethod def get_flags(cls) -> Dict[str, Flag]: """Dict[:class:`str`, :class:`Flag`]: A mapping of flag name to flag object this converter has.""" return cls.__commands_flags__.copy() @classmethod def _can_be_constructible(cls) -> bool: return all(not flag.required for flag in cls.__commands_flags__.values()) def __iter__(self) -> Iterator[Tuple[str, Any]]: for flag in self.__class__.__commands_flags__.values(): yield (flag.name, getattr(self, flag.attribute)) @classmethod async def _construct_default(cls: Type[F], ctx: Context) -> F: self: F = cls.__new__(cls) flags = cls.__commands_flags__ for flag in flags.values(): if callable(flag.default): default = await maybe_coroutine(flag.default, ctx) setattr(self, flag.attribute, default) else: setattr(self, flag.attribute, flag.default) return self def __repr__(self) -> str: pairs = ' '.join([f'{flag.attribute}={getattr(self, flag.attribute)!r}' for flag in self.get_flags().values()]) return f'<{self.__class__.__name__} {pairs}>' @classmethod def parse_flags(cls, argument: str) -> Dict[str, List[str]]: result: Dict[str, List[str]] = {} flags = cls.__commands_flags__ aliases = cls.__commands_flag_aliases__ last_position = 0 last_flag: Optional[Flag] = None case_insensitive = cls.__commands_flag_case_insensitive__ for match in cls.__commands_flag_regex__.finditer(argument): begin, end = match.span(0) key = match.group('flag') if case_insensitive: key = key.casefold() if key in aliases: key = aliases[key] flag = flags.get(key) if last_position and last_flag is not None: value = argument[last_position : begin - 1].lstrip() if not value: raise MissingFlagArgument(last_flag) try: values = result[last_flag.name] except KeyError: result[last_flag.name] = [value] else: values.append(value) last_position = end last_flag = flag # Add the remaining string to the last available flag if last_position and last_flag is not None: value = argument[last_position:].strip() if not value: raise MissingFlagArgument(last_flag) try: values = result[last_flag.name] except KeyError: result[last_flag.name] = [value] else: values.append(value) # Verification of values will come at a later stage return result @classmethod async def convert(cls: Type[F], ctx: Context, argument: str) -> F: """|coro| The method that actually converters an argument to the flag mapping. Parameters ---------- cls: Type[:class:`FlagConverter`] The flag converter class. ctx: :class:`Context` The invocation context. argument: :class:`str` The argument to convert from. Raises -------- FlagError A flag related parsing error. CommandError A command related error. Returns -------- :class:`FlagConverter` The flag converter instance with all flags parsed. """ arguments = cls.parse_flags(argument) flags = cls.__commands_flags__ self: F = cls.__new__(cls) for name, flag in flags.items(): try: values = arguments[name] except KeyError: if flag.required: raise MissingRequiredFlag(flag) else: if callable(flag.default): default = await maybe_coroutine(flag.default, ctx) setattr(self, flag.attribute, default) else: setattr(self, flag.attribute, flag.default) continue if flag.max_args > 0 and len(values) > flag.max_args: if flag.override: values = values[-flag.max_args :] else: raise TooManyFlags(flag, values) # Special case: if flag.max_args == 1: value = await convert_flag(ctx, values[0], flag) setattr(self, flag.attribute, value) continue # Another special case, tuple parsing. # Tuple parsing is basically converting arguments within the flag # So, given flag: hello 20 as the input and Tuple[str, int] as the type hint # We would receive ('hello', 20) as the resulting value # This uses the same whitespace and quoting rules as regular parameters. values = [await convert_flag(ctx, value, flag) for value in values] if flag.cast_to_dict: values = dict(values) # type: ignore setattr(self, flag.attribute, values) return self
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ext/commands/flags.py
flags.py
import itertools import copy import functools import inspect import re from typing import Optional, TYPE_CHECKING import discord.utils from .core import Group, Command from .errors import CommandError if TYPE_CHECKING: from .context import Context __all__ = ( 'Paginator', 'HelpCommand', 'DefaultHelpCommand', 'MinimalHelpCommand', ) # help -> shows info of bot on top/bottom and lists subcommands # help command -> shows detailed info of command # help command <subcommand chain> -> same as above # <description> # <command signature with aliases> # <long doc> # Cog: # <command> <shortdoc> # <command> <shortdoc> # Other Cog: # <command> <shortdoc> # No Category: # <command> <shortdoc> # Type <prefix>help command for more info on a command. # You can also type <prefix>help category for more info on a category. class Paginator: """A class that aids in paginating code blocks for Discord messages. .. container:: operations .. describe:: len(x) Returns the total number of characters in the paginator. Attributes ----------- prefix: :class:`str` The prefix inserted to every page. e.g. three backticks. suffix: :class:`str` The suffix appended at the end of every page. e.g. three backticks. max_size: :class:`int` The maximum amount of codepoints allowed in a page. linesep: :class:`str` The character string inserted between lines. e.g. a newline character. .. versionadded:: 1.7 """ def __init__(self, prefix='```', suffix='```', max_size=2000, linesep='\n'): self.prefix = prefix self.suffix = suffix self.max_size = max_size self.linesep = linesep self.clear() def clear(self): """Clears the paginator to have no pages.""" if self.prefix is not None: self._current_page = [self.prefix] self._count = len(self.prefix) + self._linesep_len # prefix + newline else: self._current_page = [] self._count = 0 self._pages = [] @property def _prefix_len(self): return len(self.prefix) if self.prefix else 0 @property def _suffix_len(self): return len(self.suffix) if self.suffix else 0 @property def _linesep_len(self): return len(self.linesep) def add_line(self, line='', *, empty=False): """Adds a line to the current page. If the line exceeds the :attr:`max_size` then an exception is raised. Parameters ----------- line: :class:`str` The line to add. empty: :class:`bool` Indicates if another empty line should be added. Raises ------ RuntimeError The line was too big for the current :attr:`max_size`. """ max_page_size = self.max_size - self._prefix_len - self._suffix_len - 2 * self._linesep_len if len(line) > max_page_size: raise RuntimeError(f'Line exceeds maximum page size {max_page_size}') if self._count + len(line) + self._linesep_len > self.max_size - self._suffix_len: self.close_page() self._count += len(line) + self._linesep_len self._current_page.append(line) if empty: self._current_page.append('') self._count += self._linesep_len def close_page(self): """Prematurely terminate a page.""" if self.suffix is not None: self._current_page.append(self.suffix) self._pages.append(self.linesep.join(self._current_page)) if self.prefix is not None: self._current_page = [self.prefix] self._count = len(self.prefix) + self._linesep_len # prefix + linesep else: self._current_page = [] self._count = 0 def __len__(self): total = sum(len(p) for p in self._pages) return total + self._count @property def pages(self): """List[:class:`str`]: Returns the rendered list of pages.""" # we have more than just the prefix in our current page if len(self._current_page) > (0 if self.prefix is None else 1): self.close_page() return self._pages def __repr__(self): fmt = '<Paginator prefix: {0.prefix!r} suffix: {0.suffix!r} linesep: {0.linesep!r} max_size: {0.max_size} count: {0._count}>' return fmt.format(self) def _not_overriden(f): f.__help_command_not_overriden__ = True return f class _HelpCommandImpl(Command): def __init__(self, inject, *args, **kwargs): super().__init__(inject.command_callback, *args, **kwargs) self._original = inject self._injected = inject async def prepare(self, ctx): self._injected = injected = self._original.copy() injected.context = ctx self.callback = injected.command_callback on_error = injected.on_help_command_error if not hasattr(on_error, '__help_command_not_overriden__'): if self.cog is not None: self.on_error = self._on_error_cog_implementation else: self.on_error = on_error await super().prepare(ctx) async def _parse_arguments(self, ctx): # Make the parser think we don't have a cog so it doesn't # inject the parameter into `ctx.args`. original_cog = self.cog self.cog = None try: await super()._parse_arguments(ctx) finally: self.cog = original_cog async def _on_error_cog_implementation(self, dummy, ctx, error): await self._injected.on_help_command_error(ctx, error) @property def clean_params(self): result = self.params.copy() try: del result[next(iter(result))] except StopIteration: raise ValueError('Missing context parameter') from None else: return result def _inject_into_cog(self, cog): # Warning: hacky # Make the cog think that get_commands returns this command # as well if we inject it without modifying __cog_commands__ # since that's used for the injection and ejection of cogs. def wrapped_get_commands(*, _original=cog.get_commands): ret = _original() ret.append(self) return ret # Ditto here def wrapped_walk_commands(*, _original=cog.walk_commands): yield from _original() yield self functools.update_wrapper(wrapped_get_commands, cog.get_commands) functools.update_wrapper(wrapped_walk_commands, cog.walk_commands) cog.get_commands = wrapped_get_commands cog.walk_commands = wrapped_walk_commands self.cog = cog def _eject_cog(self): if self.cog is None: return # revert back into their original methods cog = self.cog cog.get_commands = cog.get_commands.__wrapped__ cog.walk_commands = cog.walk_commands.__wrapped__ self.cog = None class HelpCommand: r"""The base implementation for help command formatting. .. note:: Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in :issue:`2123`. This means that relying on the state of this class to be the same between command invocations would not work as expected. Attributes ------------ context: Optional[:class:`Context`] The context that invoked this help formatter. This is generally set after the help command assigned, :func:`command_callback`\, has been called. show_hidden: :class:`bool` Specifies if hidden commands should be shown in the output. Defaults to ``False``. verify_checks: Optional[:class:`bool`] Specifies if commands should have their :attr:`.Command.checks` called and verified. If ``True``, always calls :attr:`.Command.checks`. If ``None``, only calls :attr:`.Command.checks` in a guild setting. If ``False``, never calls :attr:`.Command.checks`. Defaults to ``True``. .. versionchanged:: 1.7 command_attrs: :class:`dict` A dictionary of options to pass in for the construction of the help command. This allows you to change the command behaviour without actually changing the implementation of the command. The attributes will be the same as the ones passed in the :class:`.Command` constructor. """ MENTION_TRANSFORMS = { '@everyone': '@\u200beveryone', '@here': '@\u200bhere', r'<@!?[0-9]{17,22}>': '@deleted-user', r'<@&[0-9]{17,22}>': '@deleted-role', } MENTION_PATTERN = re.compile('|'.join(MENTION_TRANSFORMS.keys())) def __new__(cls, *args, **kwargs): # To prevent race conditions of a single instance while also allowing # for settings to be passed the original arguments passed must be assigned # to allow for easier copies (which will be made when the help command is actually called) # see issue 2123 self = super().__new__(cls) # Shallow copies cannot be used in this case since it is not unusual to pass # instances that need state, e.g. Paginator or what have you into the function # The keys can be safely copied as-is since they're 99.99% certain of being # string keys deepcopy = copy.deepcopy self.__original_kwargs__ = {k: deepcopy(v) for k, v in kwargs.items()} self.__original_args__ = deepcopy(args) return self def __init__(self, **options): self.show_hidden = options.pop('show_hidden', False) self.verify_checks = options.pop('verify_checks', True) self.command_attrs = attrs = options.pop('command_attrs', {}) attrs.setdefault('name', 'help') attrs.setdefault('help', 'Shows this message') self.context: Context = discord.utils.MISSING self._command_impl = _HelpCommandImpl(self, **self.command_attrs) def copy(self): obj = self.__class__(*self.__original_args__, **self.__original_kwargs__) obj._command_impl = self._command_impl return obj def _add_to_bot(self, bot): command = _HelpCommandImpl(self, **self.command_attrs) bot.add_command(command) self._command_impl = command def _remove_from_bot(self, bot): bot.remove_command(self._command_impl.name) self._command_impl._eject_cog() def add_check(self, func): """ Adds a check to the help command. .. versionadded:: 1.4 Parameters ---------- func The function that will be used as a check. """ self._command_impl.add_check(func) def remove_check(self, func): """ Removes a check from the help command. This function is idempotent and will not raise an exception if the function is not in the command's checks. .. versionadded:: 1.4 Parameters ---------- func The function to remove from the checks. """ self._command_impl.remove_check(func) def get_bot_mapping(self): """Retrieves the bot mapping passed to :meth:`send_bot_help`.""" bot = self.context.bot mapping = {cog: cog.get_commands() for cog in bot.cogs.values()} mapping[None] = [c for c in bot.commands if c.cog is None] return mapping @property def invoked_with(self): """Similar to :attr:`Context.invoked_with` except properly handles the case where :meth:`Context.send_help` is used. If the help command was used regularly then this returns the :attr:`Context.invoked_with` attribute. Otherwise, if it the help command was called using :meth:`Context.send_help` then it returns the internal command name of the help command. Returns --------- :class:`str` The command name that triggered this invocation. """ command_name = self._command_impl.name ctx = self.context if ctx is None or ctx.command is None or ctx.command.qualified_name != command_name: return command_name return ctx.invoked_with def get_command_signature(self, command): """Retrieves the signature portion of the help page. Parameters ------------ command: :class:`Command` The command to get the signature of. Returns -------- :class:`str` The signature for the command. """ parent = command.parent entries = [] while parent is not None: if not parent.signature or parent.invoke_without_command: entries.append(parent.name) else: entries.append(parent.name + ' ' + parent.signature) parent = parent.parent parent_sig = ' '.join(reversed(entries)) if len(command.aliases) > 0: aliases = '|'.join(command.aliases) fmt = f'[{command.name}|{aliases}]' if parent_sig: fmt = parent_sig + ' ' + fmt alias = fmt else: alias = command.name if not parent_sig else parent_sig + ' ' + command.name return f'{self.context.clean_prefix}{alias} {command.signature}' def remove_mentions(self, string): """Removes mentions from the string to prevent abuse. This includes ``@everyone``, ``@here``, member mentions and role mentions. Returns ------- :class:`str` The string with mentions removed. """ def replace(obj, *, transforms=self.MENTION_TRANSFORMS): return transforms.get(obj.group(0), '@invalid') return self.MENTION_PATTERN.sub(replace, string) @property def cog(self): """A property for retrieving or setting the cog for the help command. When a cog is set for the help command, it is as-if the help command belongs to that cog. All cog special methods will apply to the help command and it will be automatically unset on unload. To unbind the cog from the help command, you can set it to ``None``. Returns -------- Optional[:class:`Cog`] The cog that is currently set for the help command. """ return self._command_impl.cog @cog.setter def cog(self, cog): # Remove whatever cog is currently valid, if any self._command_impl._eject_cog() # If a new cog is set then inject it. if cog is not None: self._command_impl._inject_into_cog(cog) def command_not_found(self, string): """|maybecoro| A method called when a command is not found in the help command. This is useful to override for i18n. Defaults to ``No command called {0} found.`` Parameters ------------ string: :class:`str` The string that contains the invalid command. Note that this has had mentions removed to prevent abuse. Returns --------- :class:`str` The string to use when a command has not been found. """ return f'No command called "{string}" found.' def subcommand_not_found(self, command, string): """|maybecoro| A method called when a command did not have a subcommand requested in the help command. This is useful to override for i18n. Defaults to either: - ``'Command "{command.qualified_name}" has no subcommands.'`` - If there is no subcommand in the ``command`` parameter. - ``'Command "{command.qualified_name}" has no subcommand named {string}'`` - If the ``command`` parameter has subcommands but not one named ``string``. Parameters ------------ command: :class:`Command` The command that did not have the subcommand requested. string: :class:`str` The string that contains the invalid subcommand. Note that this has had mentions removed to prevent abuse. Returns --------- :class:`str` The string to use when the command did not have the subcommand requested. """ if isinstance(command, Group) and len(command.all_commands) > 0: return f'Command "{command.qualified_name}" has no subcommand named {string}' return f'Command "{command.qualified_name}" has no subcommands.' async def filter_commands(self, commands, *, sort=False, key=None): """|coro| Returns a filtered list of commands and optionally sorts them. This takes into account the :attr:`verify_checks` and :attr:`show_hidden` attributes. Parameters ------------ commands: Iterable[:class:`Command`] An iterable of commands that are getting filtered. sort: :class:`bool` Whether to sort the result. key: Optional[Callable[:class:`Command`, Any]] An optional key function to pass to :func:`py:sorted` that takes a :class:`Command` as its sole parameter. If ``sort`` is passed as ``True`` then this will default as the command name. Returns --------- List[:class:`Command`] A list of commands that passed the filter. """ if sort and key is None: key = lambda c: c.name iterator = commands if self.show_hidden else filter(lambda c: not c.hidden, commands) if self.verify_checks is False: # if we do not need to verify the checks then we can just # run it straight through normally without using await. return sorted(iterator, key=key) if sort else list(iterator) if self.verify_checks is None and not self.context.guild: # if verify_checks is None and we're in a DM, don't verify return sorted(iterator, key=key) if sort else list(iterator) # if we're here then we need to check every command if it can run async def predicate(cmd): try: return await cmd.can_run(self.context) except CommandError: return False ret = [] for cmd in iterator: valid = await predicate(cmd) if valid: ret.append(cmd) if sort: ret.sort(key=key) return ret def get_max_size(self, commands): """Returns the largest name length of the specified command list. Parameters ------------ commands: Sequence[:class:`Command`] A sequence of commands to check for the largest size. Returns -------- :class:`int` The maximum width of the commands. """ as_lengths = (discord.utils._string_width(c.name) for c in commands) return max(as_lengths, default=0) def get_destination(self): """Returns the :class:`~discord.abc.Messageable` where the help command will be output. You can override this method to customise the behaviour. By default this returns the context's channel. Returns ------- :class:`.abc.Messageable` The destination where the help command will be output. """ return self.context.channel async def send_error_message(self, error): """|coro| Handles the implementation when an error happens in the help command. For example, the result of :meth:`command_not_found` will be passed here. You can override this method to customise the behaviour. By default, this sends the error message to the destination specified by :meth:`get_destination`. .. note:: You can access the invocation context with :attr:`HelpCommand.context`. Parameters ------------ error: :class:`str` The error message to display to the user. Note that this has had mentions removed to prevent abuse. """ destination = self.get_destination() await destination.send(error) @_not_overriden async def on_help_command_error(self, ctx, error): """|coro| The help command's error handler, as specified by :ref:`ext_commands_error_handler`. Useful to override if you need some specific behaviour when the error handler is called. By default this method does nothing and just propagates to the default error handlers. Parameters ------------ ctx: :class:`Context` The invocation context. error: :class:`CommandError` The error that was raised. """ pass async def send_bot_help(self, mapping): """|coro| Handles the implementation of the bot command page in the help command. This function is called when the help command is called with no arguments. It should be noted that this method does not return anything -- rather the actual message sending should be done inside this method. Well behaved subclasses should use :meth:`get_destination` to know where to send, as this is a customisation point for other users. You can override this method to customise the behaviour. .. note:: You can access the invocation context with :attr:`HelpCommand.context`. Also, the commands in the mapping are not filtered. To do the filtering you will have to call :meth:`filter_commands` yourself. Parameters ------------ mapping: Mapping[Optional[:class:`Cog`], List[:class:`Command`]] A mapping of cogs to commands that have been requested by the user for help. The key of the mapping is the :class:`~.commands.Cog` that the command belongs to, or ``None`` if there isn't one, and the value is a list of commands that belongs to that cog. """ return None async def send_cog_help(self, cog): """|coro| Handles the implementation of the cog page in the help command. This function is called when the help command is called with a cog as the argument. It should be noted that this method does not return anything -- rather the actual message sending should be done inside this method. Well behaved subclasses should use :meth:`get_destination` to know where to send, as this is a customisation point for other users. You can override this method to customise the behaviour. .. note:: You can access the invocation context with :attr:`HelpCommand.context`. To get the commands that belong to this cog see :meth:`Cog.get_commands`. The commands returned not filtered. To do the filtering you will have to call :meth:`filter_commands` yourself. Parameters ----------- cog: :class:`Cog` The cog that was requested for help. """ return None async def send_group_help(self, group): """|coro| Handles the implementation of the group page in the help command. This function is called when the help command is called with a group as the argument. It should be noted that this method does not return anything -- rather the actual message sending should be done inside this method. Well behaved subclasses should use :meth:`get_destination` to know where to send, as this is a customisation point for other users. You can override this method to customise the behaviour. .. note:: You can access the invocation context with :attr:`HelpCommand.context`. To get the commands that belong to this group without aliases see :attr:`Group.commands`. The commands returned not filtered. To do the filtering you will have to call :meth:`filter_commands` yourself. Parameters ----------- group: :class:`Group` The group that was requested for help. """ return None async def send_command_help(self, command): """|coro| Handles the implementation of the single command page in the help command. It should be noted that this method does not return anything -- rather the actual message sending should be done inside this method. Well behaved subclasses should use :meth:`get_destination` to know where to send, as this is a customisation point for other users. You can override this method to customise the behaviour. .. note:: You can access the invocation context with :attr:`HelpCommand.context`. .. admonition:: Showing Help :class: helpful There are certain attributes and methods that are helpful for a help command to show such as the following: - :attr:`Command.help` - :attr:`Command.brief` - :attr:`Command.short_doc` - :attr:`Command.description` - :meth:`get_command_signature` There are more than just these attributes but feel free to play around with these to help you get started to get the output that you want. Parameters ----------- command: :class:`Command` The command that was requested for help. """ return None async def prepare_help_command(self, ctx, command=None): """|coro| A low level method that can be used to prepare the help command before it does anything. For example, if you need to prepare some state in your subclass before the command does its processing then this would be the place to do it. The default implementation does nothing. .. note:: This is called *inside* the help command callback body. So all the usual rules that happen inside apply here as well. Parameters ----------- ctx: :class:`Context` The invocation context. command: Optional[:class:`str`] The argument passed to the help command. """ pass async def command_callback(self, ctx, *, command=None): """|coro| The actual implementation of the help command. It is not recommended to override this method and instead change the behaviour through the methods that actually get dispatched. - :meth:`send_bot_help` - :meth:`send_cog_help` - :meth:`send_group_help` - :meth:`send_command_help` - :meth:`get_destination` - :meth:`command_not_found` - :meth:`subcommand_not_found` - :meth:`send_error_message` - :meth:`on_help_command_error` - :meth:`prepare_help_command` """ await self.prepare_help_command(ctx, command) bot = ctx.bot if command is None: mapping = self.get_bot_mapping() return await self.send_bot_help(mapping) # Check if it's a cog cog = bot.get_cog(command) if cog is not None: return await self.send_cog_help(cog) maybe_coro = discord.utils.maybe_coroutine # If it's not a cog then it's a command. # Since we want to have detailed errors when someone # passes an invalid subcommand, we need to walk through # the command group chain ourselves. keys = command.split(' ') cmd = bot.all_commands.get(keys[0]) if cmd is None: string = await maybe_coro(self.command_not_found, self.remove_mentions(keys[0])) return await self.send_error_message(string) for key in keys[1:]: try: found = cmd.all_commands.get(key) except AttributeError: string = await maybe_coro(self.subcommand_not_found, cmd, self.remove_mentions(key)) return await self.send_error_message(string) else: if found is None: string = await maybe_coro(self.subcommand_not_found, cmd, self.remove_mentions(key)) return await self.send_error_message(string) cmd = found if isinstance(cmd, Group): return await self.send_group_help(cmd) else: return await self.send_command_help(cmd) class DefaultHelpCommand(HelpCommand): """The implementation of the default help command. This inherits from :class:`HelpCommand`. It extends it with the following attributes. Attributes ------------ width: :class:`int` The maximum number of characters that fit in a line. Defaults to 80. sort_commands: :class:`bool` Whether to sort the commands in the output alphabetically. Defaults to ``True``. dm_help: Optional[:class:`bool`] A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to ``True``, then all help output is DM'd. If ``False``, none of the help output is DM'd. If ``None``, then the bot will only DM when the help message becomes too long (dictated by more than :attr:`dm_help_threshold` characters). Defaults to ``False``. dm_help_threshold: Optional[:class:`int`] The number of characters the paginator must accumulate before getting DM'd to the user if :attr:`dm_help` is set to ``None``. Defaults to 1000. indent: :class:`int` How much to indent the commands from a heading. Defaults to ``2``. commands_heading: :class:`str` The command list's heading string used when the help command is invoked with a category name. Useful for i18n. Defaults to ``"Commands:"`` no_category: :class:`str` The string used when there is a command which does not belong to any category(cog). Useful for i18n. Defaults to ``"No Category"`` paginator: :class:`Paginator` The paginator used to paginate the help command output. """ def __init__(self, **options): self.width = options.pop('width', 80) self.indent = options.pop('indent', 2) self.sort_commands = options.pop('sort_commands', True) self.dm_help = options.pop('dm_help', False) self.dm_help_threshold = options.pop('dm_help_threshold', 1000) self.commands_heading = options.pop('commands_heading', "Commands:") self.no_category = options.pop('no_category', 'No Category') self.paginator = options.pop('paginator', None) if self.paginator is None: self.paginator = Paginator() super().__init__(**options) def shorten_text(self, text): """:class:`str`: Shortens text to fit into the :attr:`width`.""" if len(text) > self.width: return text[:self.width - 3].rstrip() + '...' return text def get_ending_note(self): """:class:`str`: Returns help command's ending note. This is mainly useful to override for i18n purposes.""" command_name = self.invoked_with return ( f"Type {self.context.clean_prefix}{command_name} command for more info on a command.\n" f"You can also type {self.context.clean_prefix}{command_name} category for more info on a category." ) def add_indented_commands(self, commands, *, heading, max_size=None): """Indents a list of commands after the specified heading. The formatting is added to the :attr:`paginator`. The default implementation is the command name indented by :attr:`indent` spaces, padded to ``max_size`` followed by the command's :attr:`Command.short_doc` and then shortened to fit into the :attr:`width`. Parameters ----------- commands: Sequence[:class:`Command`] A list of commands to indent for output. heading: :class:`str` The heading to add to the output. This is only added if the list of commands is greater than 0. max_size: Optional[:class:`int`] The max size to use for the gap between indents. If unspecified, calls :meth:`~HelpCommand.get_max_size` on the commands parameter. """ if not commands: return self.paginator.add_line(heading) max_size = max_size or self.get_max_size(commands) get_width = discord.utils._string_width for command in commands: name = command.name width = max_size - (get_width(name) - len(name)) entry = f'{self.indent * " "}{name:<{width}} {command.short_doc}' self.paginator.add_line(self.shorten_text(entry)) async def send_pages(self): """A helper utility to send the page output from :attr:`paginator` to the destination.""" destination = self.get_destination() for page in self.paginator.pages: await destination.send(page) def add_command_formatting(self, command): """A utility function to format the non-indented block of commands and groups. Parameters ------------ command: :class:`Command` The command to format. """ if command.description: self.paginator.add_line(command.description, empty=True) signature = self.get_command_signature(command) self.paginator.add_line(signature, empty=True) if command.help: try: self.paginator.add_line(command.help, empty=True) except RuntimeError: for line in command.help.splitlines(): self.paginator.add_line(line) self.paginator.add_line() def get_destination(self): ctx = self.context if self.dm_help is True: return ctx.author elif self.dm_help is None and len(self.paginator) > self.dm_help_threshold: return ctx.author else: return ctx.channel async def prepare_help_command(self, ctx, command): self.paginator.clear() await super().prepare_help_command(ctx, command) async def send_bot_help(self, mapping): ctx = self.context bot = ctx.bot if bot.description: # <description> portion self.paginator.add_line(bot.description, empty=True) no_category = f'\u200b{self.no_category}:' def get_category(command, *, no_category=no_category): cog = command.cog return cog.qualified_name + ':' if cog is not None else no_category filtered = await self.filter_commands(bot.commands, sort=True, key=get_category) max_size = self.get_max_size(filtered) to_iterate = itertools.groupby(filtered, key=get_category) # Now we can add the commands to the page. for category, commands in to_iterate: commands = sorted(commands, key=lambda c: c.name) if self.sort_commands else list(commands) self.add_indented_commands(commands, heading=category, max_size=max_size) note = self.get_ending_note() if note: self.paginator.add_line() self.paginator.add_line(note) await self.send_pages() async def send_command_help(self, command): self.add_command_formatting(command) self.paginator.close_page() await self.send_pages() async def send_group_help(self, group): self.add_command_formatting(group) filtered = await self.filter_commands(group.commands, sort=self.sort_commands) self.add_indented_commands(filtered, heading=self.commands_heading) if filtered: note = self.get_ending_note() if note: self.paginator.add_line() self.paginator.add_line(note) await self.send_pages() async def send_cog_help(self, cog): if cog.description: self.paginator.add_line(cog.description, empty=True) filtered = await self.filter_commands(cog.get_commands(), sort=self.sort_commands) self.add_indented_commands(filtered, heading=self.commands_heading) note = self.get_ending_note() if note: self.paginator.add_line() self.paginator.add_line(note) await self.send_pages() class MinimalHelpCommand(HelpCommand): """An implementation of a help command with minimal output. This inherits from :class:`HelpCommand`. Attributes ------------ sort_commands: :class:`bool` Whether to sort the commands in the output alphabetically. Defaults to ``True``. commands_heading: :class:`str` The command list's heading string used when the help command is invoked with a category name. Useful for i18n. Defaults to ``"Commands"`` aliases_heading: :class:`str` The alias list's heading string used to list the aliases of the command. Useful for i18n. Defaults to ``"Aliases:"``. dm_help: Optional[:class:`bool`] A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to ``True``, then all help output is DM'd. If ``False``, none of the help output is DM'd. If ``None``, then the bot will only DM when the help message becomes too long (dictated by more than :attr:`dm_help_threshold` characters). Defaults to ``False``. dm_help_threshold: Optional[:class:`int`] The number of characters the paginator must accumulate before getting DM'd to the user if :attr:`dm_help` is set to ``None``. Defaults to 1000. no_category: :class:`str` The string used when there is a command which does not belong to any category(cog). Useful for i18n. Defaults to ``"No Category"`` paginator: :class:`Paginator` The paginator used to paginate the help command output. """ def __init__(self, **options): self.sort_commands = options.pop('sort_commands', True) self.commands_heading = options.pop('commands_heading', "Commands") self.dm_help = options.pop('dm_help', False) self.dm_help_threshold = options.pop('dm_help_threshold', 1000) self.aliases_heading = options.pop('aliases_heading', "Aliases:") self.no_category = options.pop('no_category', 'No Category') self.paginator = options.pop('paginator', None) if self.paginator is None: self.paginator = Paginator(suffix=None, prefix=None) super().__init__(**options) async def send_pages(self): """A helper utility to send the page output from :attr:`paginator` to the destination.""" destination = self.get_destination() for page in self.paginator.pages: await destination.send(page) def get_opening_note(self): """Returns help command's opening note. This is mainly useful to override for i18n purposes. The default implementation returns :: Use `{prefix}{command_name} [command]` for more info on a command. You can also use `{prefix}{command_name} [category]` for more info on a category. Returns ------- :class:`str` The help command opening note. """ command_name = self.invoked_with return ( f"Use `{self.context.clean_prefix}{command_name} [command]` for more info on a command.\n" f"You can also use `{self.context.clean_prefix}{command_name} [category]` for more info on a category." ) def get_command_signature(self, command): return f'{self.context.clean_prefix}{command.qualified_name} {command.signature}' def get_ending_note(self): """Return the help command's ending note. This is mainly useful to override for i18n purposes. The default implementation does nothing. Returns ------- :class:`str` The help command ending note. """ return None def add_bot_commands_formatting(self, commands, heading): """Adds the minified bot heading with commands to the output. The formatting should be added to the :attr:`paginator`. The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line. Parameters ----------- commands: Sequence[:class:`Command`] A list of commands that belong to the heading. heading: :class:`str` The heading to add to the line. """ if commands: # U+2002 Middle Dot joined = '\u2002'.join(c.name for c in commands) self.paginator.add_line(f'__**{heading}**__') self.paginator.add_line(joined) def add_subcommand_formatting(self, command): """Adds formatting information on a subcommand. The formatting should be added to the :attr:`paginator`. The default implementation is the prefix and the :attr:`Command.qualified_name` optionally followed by an En dash and the command's :attr:`Command.short_doc`. Parameters ----------- command: :class:`Command` The command to show information of. """ fmt = '{0}{1} \N{EN DASH} {2}' if command.short_doc else '{0}{1}' self.paginator.add_line(fmt.format(self.context.clean_prefix, command.qualified_name, command.short_doc)) def add_aliases_formatting(self, aliases): """Adds the formatting information on a command's aliases. The formatting should be added to the :attr:`paginator`. The default implementation is the :attr:`aliases_heading` bolded followed by a comma separated list of aliases. This is not called if there are no aliases to format. Parameters ----------- aliases: Sequence[:class:`str`] A list of aliases to format. """ self.paginator.add_line(f'**{self.aliases_heading}** {", ".join(aliases)}', empty=True) def add_command_formatting(self, command): """A utility function to format commands and groups. Parameters ------------ command: :class:`Command` The command to format. """ if command.description: self.paginator.add_line(command.description, empty=True) signature = self.get_command_signature(command) if command.aliases: self.paginator.add_line(signature) self.add_aliases_formatting(command.aliases) else: self.paginator.add_line(signature, empty=True) if command.help: try: self.paginator.add_line(command.help, empty=True) except RuntimeError: for line in command.help.splitlines(): self.paginator.add_line(line) self.paginator.add_line() def get_destination(self): ctx = self.context if self.dm_help is True: return ctx.author elif self.dm_help is None and len(self.paginator) > self.dm_help_threshold: return ctx.author else: return ctx.channel async def prepare_help_command(self, ctx, command): self.paginator.clear() await super().prepare_help_command(ctx, command) async def send_bot_help(self, mapping): ctx = self.context bot = ctx.bot if bot.description: self.paginator.add_line(bot.description, empty=True) note = self.get_opening_note() if note: self.paginator.add_line(note, empty=True) no_category = f'\u200b{self.no_category}' def get_category(command, *, no_category=no_category): cog = command.cog return cog.qualified_name if cog is not None else no_category filtered = await self.filter_commands(bot.commands, sort=True, key=get_category) to_iterate = itertools.groupby(filtered, key=get_category) for category, commands in to_iterate: commands = sorted(commands, key=lambda c: c.name) if self.sort_commands else list(commands) self.add_bot_commands_formatting(commands, category) note = self.get_ending_note() if note: self.paginator.add_line() self.paginator.add_line(note) await self.send_pages() async def send_cog_help(self, cog): bot = self.context.bot if bot.description: self.paginator.add_line(bot.description, empty=True) note = self.get_opening_note() if note: self.paginator.add_line(note, empty=True) if cog.description: self.paginator.add_line(cog.description, empty=True) filtered = await self.filter_commands(cog.get_commands(), sort=self.sort_commands) if filtered: self.paginator.add_line(f'**{cog.qualified_name} {self.commands_heading}**') for command in filtered: self.add_subcommand_formatting(command) note = self.get_ending_note() if note: self.paginator.add_line() self.paginator.add_line(note) await self.send_pages() async def send_group_help(self, group): self.add_command_formatting(group) filtered = await self.filter_commands(group.commands, sort=self.sort_commands) if filtered: note = self.get_opening_note() if note: self.paginator.add_line(note, empty=True) self.paginator.add_line(f'**{self.commands_heading}**') for command in filtered: self.add_subcommand_formatting(command) note = self.get_ending_note() if note: self.paginator.add_line() self.paginator.add_line(note) await self.send_pages() async def send_command_help(self, command): self.add_command_formatting(command) self.paginator.close_page() await self.send_pages()
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ext/commands/help.py
help.py
from __future__ import annotations import asyncio import collections import collections.abc import inspect import importlib.util import sys import traceback import types from typing import Any, Callable, Mapping, List, Dict, TYPE_CHECKING, Optional, TypeVar, Type, Union import discord from .core import GroupMixin from .view import StringView from .context import Context from . import errors from .help import HelpCommand, DefaultHelpCommand from .cog import Cog if TYPE_CHECKING: import importlib.machinery from discord.message import Message from ._types import ( Check, CoroFunc, ) __all__ = ( 'when_mentioned', 'when_mentioned_or', 'Bot', 'AutoShardedBot', ) MISSING: Any = discord.utils.MISSING T = TypeVar('T') CFT = TypeVar('CFT', bound='CoroFunc') CXT = TypeVar('CXT', bound='Context') def when_mentioned(bot: Union[Bot, AutoShardedBot], msg: Message) -> List[str]: """A callable that implements a command prefix equivalent to being mentioned. These are meant to be passed into the :attr:`.Bot.command_prefix` attribute. """ # bot.user will never be None when this is called return [f'<@{bot.user.id}> ', f'<@!{bot.user.id}> '] # type: ignore def when_mentioned_or(*prefixes: str) -> Callable[[Union[Bot, AutoShardedBot], Message], List[str]]: """A callable that implements when mentioned or other prefixes provided. These are meant to be passed into the :attr:`.Bot.command_prefix` attribute. Example -------- .. code-block:: python3 bot = commands.Bot(command_prefix=commands.when_mentioned_or('!')) .. note:: This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example: .. code-block:: python3 async def get_prefix(bot, message): extras = await prefixes_for(message.guild) # returns a list return commands.when_mentioned_or(*extras)(bot, message) See Also ---------- :func:`.when_mentioned` """ def inner(bot, msg): r = list(prefixes) r = when_mentioned(bot, msg) + r return r return inner def _is_submodule(parent: str, child: str) -> bool: return parent == child or child.startswith(parent + ".") class _DefaultRepr: def __repr__(self): return '<default-help-command>' _default = _DefaultRepr() class BotBase(GroupMixin): def __init__(self, command_prefix, help_command=_default, description=None, **options): super().__init__(**options) self.command_prefix = command_prefix self.extra_events: Dict[str, List[CoroFunc]] = {} self.__cogs: Dict[str, Cog] = {} self.__extensions: Dict[str, types.ModuleType] = {} self._checks: List[Check] = [] self._check_once = [] self._before_invoke = None self._after_invoke = None self._help_command = None self.description = inspect.cleandoc(description) if description else '' self.owner_id = options.get('owner_id') self.owner_ids = options.get('owner_ids', set()) self.strip_after_prefix = options.get('strip_after_prefix', False) if self.owner_id and self.owner_ids: raise TypeError('Both owner_id and owner_ids are set.') if self.owner_ids and not isinstance(self.owner_ids, collections.abc.Collection): raise TypeError(f'owner_ids must be a collection not {self.owner_ids.__class__!r}') if help_command is _default: self.help_command = DefaultHelpCommand() else: self.help_command = help_command # internal helpers def dispatch(self, event_name: str, *args: Any, **kwargs: Any) -> None: # super() will resolve to Client super().dispatch(event_name, *args, **kwargs) # type: ignore ev = 'on_' + event_name for event in self.extra_events.get(ev, []): self._schedule_event(event, ev, *args, **kwargs) # type: ignore @discord.utils.copy_doc(discord.Client.close) async def close(self) -> None: for extension in tuple(self.__extensions): try: self.unload_extension(extension) except Exception: pass for cog in tuple(self.__cogs): try: self.remove_cog(cog) except Exception: pass await super().close() # type: ignore async def on_command_error(self, context: Context, exception: errors.CommandError) -> None: """|coro| The default command error handler provided by the bot. By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. This only fires if you do not specify any listeners for command error. """ if self.extra_events.get('on_command_error', None): return command = context.command if command and command.has_error_handler(): return cog = context.cog if cog and cog.has_error_handler(): return print(f'Ignoring exception in command {context.command}:', file=sys.stderr) traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr) # global check registration def check(self, func: T) -> T: r"""A decorator that adds a global check to the bot. A global check is similar to a :func:`.check` that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has. .. note:: This function can either be a regular function or a coroutine. Similar to a command :func:`.check`\, this takes a single parameter of type :class:`.Context` and can only raise exceptions inherited from :exc:`.CommandError`. Example --------- .. code-block:: python3 @bot.check def check_commands(ctx): return ctx.command.qualified_name in allowed_commands """ # T was used instead of Check to ensure the type matches on return self.add_check(func) # type: ignore return func def add_check(self, func: Check, *, call_once: bool = False) -> None: """Adds a global check to the bot. This is the non-decorator interface to :meth:`.check` and :meth:`.check_once`. Parameters ----------- func The function that was used as a global check. call_once: :class:`bool` If the function should only be called once per :meth:`.invoke` call. """ if call_once: self._check_once.append(func) else: self._checks.append(func) def remove_check(self, func: Check, *, call_once: bool = False) -> None: """Removes a global check from the bot. This function is idempotent and will not raise an exception if the function is not in the global checks. Parameters ----------- func The function to remove from the global checks. call_once: :class:`bool` If the function was added with ``call_once=True`` in the :meth:`.Bot.add_check` call or using :meth:`.check_once`. """ l = self._check_once if call_once else self._checks try: l.remove(func) except ValueError: pass def check_once(self, func: CFT) -> CFT: r"""A decorator that adds a "call once" global check to the bot. Unlike regular global checks, this one is called only once per :meth:`.invoke` call. Regular global checks are called whenever a command is called or :meth:`.Command.can_run` is called. This type of check bypasses that and ensures that it's called only once, even inside the default help command. .. note:: When using this function the :class:`.Context` sent to a group subcommand may only parse the parent command and not the subcommands due to it being invoked once per :meth:`.Bot.invoke` call. .. note:: This function can either be a regular function or a coroutine. Similar to a command :func:`.check`\, this takes a single parameter of type :class:`.Context` and can only raise exceptions inherited from :exc:`.CommandError`. Example --------- .. code-block:: python3 @bot.check_once def whitelist(ctx): return ctx.message.author.id in my_whitelist """ self.add_check(func, call_once=True) return func async def can_run(self, ctx: Context, *, call_once: bool = False) -> bool: data = self._check_once if call_once else self._checks if len(data) == 0: return True # type-checker doesn't distinguish between functions and methods return await discord.utils.async_all(f(ctx) for f in data) # type: ignore async def is_owner(self, user: discord.User) -> bool: """|coro| Checks if a :class:`~discord.User` or :class:`~discord.Member` is the owner of this bot. If an :attr:`owner_id` is not set, it is fetched automatically through the use of :meth:`~.Bot.application_info`. .. versionchanged:: 1.3 The function also checks if the application is team-owned if :attr:`owner_ids` is not set. Parameters ----------- user: :class:`.abc.User` The user to check for. Returns -------- :class:`bool` Whether the user is the owner. """ if self.owner_id: return user.id == self.owner_id elif self.owner_ids: return user.id in self.owner_ids else: app = await self.application_info() # type: ignore if app.team: self.owner_ids = ids = {m.id for m in app.team.members} return user.id in ids else: self.owner_id = owner_id = app.owner.id return user.id == owner_id def before_invoke(self, coro: CFT) -> CFT: """A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required. This pre-invoke hook takes a sole parameter, a :class:`.Context`. .. note:: The :meth:`~.Bot.before_invoke` and :meth:`~.Bot.after_invoke` hooks are only called if all checks and argument parsing procedures pass without error. If any check or argument parsing procedures fail then the hooks are not called. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the pre-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke = coro return coro def after_invoke(self, coro: CFT) -> CFT: r"""A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required. This post-invoke hook takes a sole parameter, a :class:`.Context`. .. note:: Similar to :meth:`~.Bot.before_invoke`\, this is not called unless checks and argument parsing procedures succeed. This hook is, however, **always** called regardless of the internal command callback raising an error (i.e. :exc:`.CommandInvokeError`\). This makes it ideal for clean-up scenarios. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the post-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must be a coroutine.') self._after_invoke = coro return coro # listener registration def add_listener(self, func: CoroFunc, name: str = MISSING) -> None: """The non decorator alternative to :meth:`.listen`. Parameters ----------- func: :ref:`coroutine <coroutine>` The function to call. name: :class:`str` The name of the event to listen for. Defaults to ``func.__name__``. Example -------- .. code-block:: python3 async def on_ready(): pass async def my_message(message): pass bot.add_listener(on_ready) bot.add_listener(my_message, 'on_message') """ name = func.__name__ if name is MISSING else name if not asyncio.iscoroutinefunction(func): raise TypeError('Listeners must be coroutines') if name in self.extra_events: self.extra_events[name].append(func) else: self.extra_events[name] = [func] def remove_listener(self, func: CoroFunc, name: str = MISSING) -> None: """Removes a listener from the pool of listeners. Parameters ----------- func The function that was used as a listener to remove. name: :class:`str` The name of the event we want to remove. Defaults to ``func.__name__``. """ name = func.__name__ if name is MISSING else name if name in self.extra_events: try: self.extra_events[name].remove(func) except ValueError: pass def listen(self, name: str = MISSING) -> Callable[[CFT], CFT]: """A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as :func:`.on_ready` The functions being listened to must be a :ref:`coroutine <coroutine>`. Example -------- .. code-block:: python3 @bot.listen() async def on_message(message): print('one') # in some other file... @bot.listen('on_message') async def my_message(message): print('two') Would print one and two in an unspecified order. Raises ------- TypeError The function being listened to is not a coroutine. """ def decorator(func: CFT) -> CFT: self.add_listener(func, name) return func return decorator # cogs def add_cog(self, cog: Cog, *, override: bool = False) -> None: """Adds a "cog" to the bot. A cog is a class that has its own event listeners and commands. .. versionchanged:: 2.0 :exc:`.ClientException` is raised when a cog with the same name is already loaded. Parameters ----------- cog: :class:`.Cog` The cog to register to the bot. override: :class:`bool` If a previously loaded cog with the same name should be ejected instead of raising an error. .. versionadded:: 2.0 Raises ------- TypeError The cog does not inherit from :class:`.Cog`. CommandError An error happened during loading. .ClientException A cog with the same name is already loaded. """ if not isinstance(cog, Cog): raise TypeError('cogs must derive from Cog') cog_name = cog.__cog_name__ existing = self.__cogs.get(cog_name) if existing is not None: if not override: raise discord.ClientException(f'Cog named {cog_name!r} already loaded') self.remove_cog(cog_name) cog = cog._inject(self) self.__cogs[cog_name] = cog def get_cog(self, name: str) -> Optional[Cog]: """Gets the cog instance requested. If the cog is not found, ``None`` is returned instead. Parameters ----------- name: :class:`str` The name of the cog you are requesting. This is equivalent to the name passed via keyword argument in class creation or the class name if unspecified. Returns -------- Optional[:class:`Cog`] The cog that was requested. If not found, returns ``None``. """ return self.__cogs.get(name) def remove_cog(self, name: str) -> Optional[Cog]: """Removes a cog from the bot and returns it. All registered commands and event listeners that the cog has registered will be removed as well. If no cog is found then this method has no effect. Parameters ----------- name: :class:`str` The name of the cog to remove. Returns ------- Optional[:class:`.Cog`] The cog that was removed. ``None`` if not found. """ cog = self.__cogs.pop(name, None) if cog is None: return help_command = self._help_command if help_command and help_command.cog is cog: help_command.cog = None cog._eject(self) return cog @property def cogs(self) -> Mapping[str, Cog]: """Mapping[:class:`str`, :class:`Cog`]: A read-only mapping of cog name to cog.""" return types.MappingProxyType(self.__cogs) # extensions def _remove_module_references(self, name: str) -> None: # find all references to the module # remove the cogs registered from the module for cogname, cog in self.__cogs.copy().items(): if _is_submodule(name, cog.__module__): self.remove_cog(cogname) # remove all the commands from the module for cmd in self.all_commands.copy().values(): if cmd.module is not None and _is_submodule(name, cmd.module): if isinstance(cmd, GroupMixin): cmd.recursively_remove_all_commands() self.remove_command(cmd.name) # remove all the listeners from the module for event_list in self.extra_events.copy().values(): remove = [] for index, event in enumerate(event_list): if event.__module__ is not None and _is_submodule(name, event.__module__): remove.append(index) for index in reversed(remove): del event_list[index] def _call_module_finalizers(self, lib: types.ModuleType, key: str) -> None: try: func = getattr(lib, 'teardown') except AttributeError: pass else: try: func(self) except Exception: pass finally: self.__extensions.pop(key, None) sys.modules.pop(key, None) name = lib.__name__ for module in list(sys.modules.keys()): if _is_submodule(name, module): del sys.modules[module] def _load_from_module_spec(self, spec: importlib.machinery.ModuleSpec, key: str) -> None: # precondition: key not in self.__extensions lib = importlib.util.module_from_spec(spec) sys.modules[key] = lib try: spec.loader.exec_module(lib) # type: ignore except Exception as e: del sys.modules[key] raise errors.ExtensionFailed(key, e) from e try: setup = getattr(lib, 'setup') except AttributeError: del sys.modules[key] raise errors.NoEntryPointError(key) try: setup(self) except Exception as e: del sys.modules[key] self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, key) raise errors.ExtensionFailed(key, e) from e else: self.__extensions[key] = lib def _resolve_name(self, name: str, package: Optional[str]) -> str: try: return importlib.util.resolve_name(name, package) except ImportError: raise errors.ExtensionNotFound(name) def load_extension(self, name: str, *, package: Optional[str] = None) -> None: """Loads an extension. An extension is a python module that contains commands, cogs, or listeners. An extension must have a global function, ``setup`` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the ``bot``. Parameters ------------ name: :class:`str` The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. package: Optional[:class:`str`] The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g ``.foo.test``. Defaults to ``None``. .. versionadded:: 1.7 Raises -------- ExtensionNotFound The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided ``package`` parameter. ExtensionAlreadyLoaded The extension is already loaded. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension or its setup function had an execution error. """ name = self._resolve_name(name, package) if name in self.__extensions: raise errors.ExtensionAlreadyLoaded(name) spec = importlib.util.find_spec(name) if spec is None: raise errors.ExtensionNotFound(name) self._load_from_module_spec(spec, name) def unload_extension(self, name: str, *, package: Optional[str] = None) -> None: """Unloads an extension. When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported. The extension can provide an optional global function, ``teardown``, to do miscellaneous clean-up if necessary. This function takes a single parameter, the ``bot``, similar to ``setup`` from :meth:`~.Bot.load_extension`. Parameters ------------ name: :class:`str` The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. package: Optional[:class:`str`] The package name to resolve relative imports with. This is required when unloading an extension using a relative path, e.g ``.foo.test``. Defaults to ``None``. .. versionadded:: 1.7 Raises ------- ExtensionNotFound The name of the extension could not be resolved using the provided ``package`` parameter. ExtensionNotLoaded The extension was not loaded. """ name = self._resolve_name(name, package) lib = self.__extensions.get(name) if lib is None: raise errors.ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) def reload_extension(self, name: str, *, package: Optional[str] = None) -> None: """Atomically reloads an extension. This replaces the extension with the same extension, only refreshed. This is equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension` except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state. Parameters ------------ name: :class:`str` The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. package: Optional[:class:`str`] The package name to resolve relative imports with. This is required when reloading an extension using a relative path, e.g ``.foo.test``. Defaults to ``None``. .. versionadded:: 1.7 Raises ------- ExtensionNotLoaded The extension was not loaded. ExtensionNotFound The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided ``package`` parameter. NoEntryPointError The extension does not have a setup function. ExtensionFailed The extension setup function had an execution error. """ name = self._resolve_name(name, package) lib = self.__extensions.get(name) if lib is None: raise errors.ExtensionNotLoaded(name) # get the previous module states from sys modules modules = { name: module for name, module in sys.modules.items() if _is_submodule(lib.__name__, name) } try: # Unload and then load the module... self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) self.load_extension(name) except Exception: # if the load failed, the remnants should have been # cleaned from the load_extension function call # so let's load it from our old compiled library. lib.setup(self) # type: ignore self.__extensions[name] = lib # revert sys.modules back to normal and raise back to caller sys.modules.update(modules) raise @property def extensions(self) -> Mapping[str, types.ModuleType]: """Mapping[:class:`str`, :class:`py:types.ModuleType`]: A read-only mapping of extension name to extension.""" return types.MappingProxyType(self.__extensions) # help command stuff @property def help_command(self) -> Optional[HelpCommand]: return self._help_command @help_command.setter def help_command(self, value: Optional[HelpCommand]) -> None: if value is not None: if not isinstance(value, HelpCommand): raise TypeError('help_command must be a subclass of HelpCommand') if self._help_command is not None: self._help_command._remove_from_bot(self) self._help_command = value value._add_to_bot(self) elif self._help_command is not None: self._help_command._remove_from_bot(self) self._help_command = None else: self._help_command = None # command processing async def get_prefix(self, message: Message) -> Union[List[str], str]: """|coro| Retrieves the prefix the bot is listening to with the message as a context. Parameters ----------- message: :class:`discord.Message` The message context to get the prefix of. Returns -------- Union[List[:class:`str`], :class:`str`] A list of prefixes or a single prefix that the bot is listening for. """ prefix = ret = self.command_prefix if callable(prefix): ret = await discord.utils.maybe_coroutine(prefix, self, message) if not isinstance(ret, str): try: ret = list(ret) except TypeError: # It's possible that a generator raised this exception. Don't # replace it with our own error if that's the case. if isinstance(ret, collections.abc.Iterable): raise raise TypeError("command_prefix must be plain string, iterable of strings, or callable " f"returning either of these, not {ret.__class__.__name__}") if not ret: raise ValueError("Iterable command_prefix must contain at least one prefix") return ret async def get_context(self, message: Message, *, cls: Type[CXT] = Context) -> CXT: r"""|coro| Returns the invocation context from the message. This is a more low-level counter-part for :meth:`.process_commands` to allow users more fine grained control over the processing. The returned context is not guaranteed to be a valid invocation context, :attr:`.Context.valid` must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under :meth:`~.Bot.invoke`. Parameters ----------- message: :class:`discord.Message` The message to get the invocation context from. cls The factory class that will be used to create the context. By default, this is :class:`.Context`. Should a custom class be provided, it must be similar enough to :class:`.Context`\'s interface. Returns -------- :class:`.Context` The invocation context. The type of this can change via the ``cls`` parameter. """ view = StringView(message.content) ctx = cls(prefix=None, view=view, bot=self, message=message) if message.author.id == self.user.id: # type: ignore return ctx prefix = await self.get_prefix(message) invoked_prefix = prefix if isinstance(prefix, str): if not view.skip_string(prefix): return ctx else: try: # if the context class' __init__ consumes something from the view this # will be wrong. That seems unreasonable though. if message.content.startswith(tuple(prefix)): invoked_prefix = discord.utils.find(view.skip_string, prefix) else: return ctx except TypeError: if not isinstance(prefix, list): raise TypeError("get_prefix must return either a string or a list of string, " f"not {prefix.__class__.__name__}") # It's possible a bad command_prefix got us here. for value in prefix: if not isinstance(value, str): raise TypeError("Iterable command_prefix or list returned from get_prefix must " f"contain only strings, not {value.__class__.__name__}") # Getting here shouldn't happen raise if self.strip_after_prefix: view.skip_ws() invoker = view.get_word() ctx.invoked_with = invoker # type-checker fails to narrow invoked_prefix type. ctx.prefix = invoked_prefix # type: ignore ctx.command = self.all_commands.get(invoker) return ctx async def invoke(self, ctx: Context) -> None: """|coro| Invokes the command given under the invocation context and handles all the internal event dispatch mechanisms. Parameters ----------- ctx: :class:`.Context` The invocation context to invoke. """ if ctx.command is not None: self.dispatch('command', ctx) try: if await self.can_run(ctx, call_once=True): await ctx.command.invoke(ctx) else: raise errors.CheckFailure('The global check once functions failed.') except errors.CommandError as exc: await ctx.command.dispatch_error(ctx, exc) else: self.dispatch('command_completion', ctx) elif ctx.invoked_with: exc = errors.CommandNotFound(f'Command "{ctx.invoked_with}" is not found') self.dispatch('command_error', ctx, exc) async def process_commands(self, message: Message) -> None: """|coro| This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered. By default, this coroutine is called inside the :func:`.on_message` event. If you choose to override the :func:`.on_message` event, then you should invoke this coroutine as well. This is built using other low level tools, and is equivalent to a call to :meth:`~.Bot.get_context` followed by a call to :meth:`~.Bot.invoke`. This also checks if the message's author is a bot and doesn't call :meth:`~.Bot.get_context` or :meth:`~.Bot.invoke` if so. Parameters ----------- message: :class:`discord.Message` The message to process commands for. """ if message.author.bot: return ctx = await self.get_context(message) await self.invoke(ctx) async def on_message(self, message): await self.process_commands(message) class Bot(BotBase, discord.Client): """Represents a discord bot. This class is a subclass of :class:`discord.Client` and as a result anything that you can do with a :class:`discord.Client` you can do with this bot. This class also subclasses :class:`.GroupMixin` to provide the functionality to manage commands. Attributes ----------- command_prefix The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and :class:`discord.Message` as its second parameter and returns the prefix. This is to facilitate "dynamic" command prefixes. This callable can be either a regular function or a coroutine. An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as it's likely to cause performance issues and unintended command invocations. The command prefix could also be an iterable of strings indicating that multiple checks for the prefix should be used and the first one to match will be the invocation prefix. You can get this prefix via :attr:`.Context.prefix`. To avoid confusion empty iterables are not allowed. .. note:: When passing multiple prefixes be careful to not pass a prefix that matches a longer prefix occurring later in the sequence. For example, if the command prefix is ``('!', '!?')`` the ``'!?'`` prefix will never be matched to any message as the previous one matches messages starting with ``!?``. This is especially important when passing an empty string, it should always be last as no prefix after it will be matched. case_insensitive: :class:`bool` Whether the commands should be case insensitive. Defaults to ``False``. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well. description: :class:`str` The content prefixed into the default help message. help_command: Optional[:class:`.HelpCommand`] The help command implementation to use. This can be dynamically set at runtime. To remove the help command pass ``None``. For more information on implementing a help command, see :ref:`ext_commands_help_command`. owner_id: Optional[:class:`int`] The user ID that owns the bot. If this is not set and is then queried via :meth:`.is_owner` then it is fetched automatically using :meth:`~.Bot.application_info`. owner_ids: Optional[Collection[:class:`int`]] The user IDs that owns the bot. This is similar to :attr:`owner_id`. If this is not set and the application is team based, then it is fetched automatically using :meth:`~.Bot.application_info`. For performance reasons it is recommended to use a :class:`set` for the collection. You cannot set both ``owner_id`` and ``owner_ids``. .. versionadded:: 1.3 strip_after_prefix: :class:`bool` Whether to strip whitespace characters after encountering the command prefix. This allows for ``! hello`` and ``!hello`` to both work if the ``command_prefix`` is set to ``!``. Defaults to ``False``. .. versionadded:: 1.7 """ pass class AutoShardedBot(BotBase, discord.AutoShardedClient): """This is similar to :class:`.Bot` except that it is inherited from :class:`discord.AutoShardedClient` instead. """ pass
zarenacord
/zarenacord-2.0.0.tar.gz/zarenacord-2.0.0/discord/ext/commands/bot.py
bot.py
from __future__ import annotations import io import os from typing import Any, Literal, Optional, TYPE_CHECKING, Tuple, Union from .errors import DiscordException from .errors import InvalidArgument from . import utils import yarl __all__ = ( 'Asset', ) if TYPE_CHECKING: ValidStaticFormatTypes = Literal['webp', 'jpeg', 'jpg', 'png'] ValidAssetFormatTypes = Literal['webp', 'jpeg', 'jpg', 'png', 'gif'] VALID_STATIC_FORMATS = frozenset({"jpeg", "jpg", "webp", "png"}) VALID_ASSET_FORMATS = VALID_STATIC_FORMATS | {"gif"} MISSING = utils.MISSING class AssetMixin: url: str _state: Optional[Any] async def read(self) -> bytes: """|coro| Retrieves the content of this asset as a :class:`bytes` object. Raises ------ DiscordException There was no internal connection state. HTTPException Downloading the asset failed. NotFound The asset was deleted. Returns ------- :class:`bytes` The content of the asset. """ if self._state is None: raise DiscordException('Invalid state (no ConnectionState provided)') return await self._state.http.get_from_cdn(self.url) async def save(self, fp: Union[str, bytes, os.PathLike, io.BufferedIOBase], *, seek_begin: bool = True) -> int: """|coro| Saves this asset into a file-like object. Parameters ---------- fp: Union[:class:`io.BufferedIOBase`, :class:`os.PathLike`] The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead. seek_begin: :class:`bool` Whether to seek to the beginning of the file after saving is successfully done. Raises ------ DiscordException There was no internal connection state. HTTPException Downloading the asset failed. NotFound The asset was deleted. Returns -------- :class:`int` The number of bytes written. """ data = await self.read() if isinstance(fp, io.BufferedIOBase): written = fp.write(data) if seek_begin: fp.seek(0) return written else: with open(fp, 'wb') as f: return f.write(data) 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): self._state = state self._url = url self._animated = animated self._key = key @classmethod 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, ) @classmethod 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, ) @classmethod 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, ) @classmethod 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, ) @classmethod 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, ) @classmethod def _from_guild_image(cls, state, guild_id: int, image: str, path: str) -> Asset: return cls( state, url=f'{cls.BASE}/{path}/{guild_id}/{image}.png?size=1024', key=image, animated=False, ) @classmethod 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, ) @classmethod 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, ) @classmethod 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 __str__(self) -> str: return self._url def __len__(self) -> int: return len(self._url) def __repr__(self): 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) @property def url(self) -> str: """:class:`str`: Returns the underlying URL of the asset.""" return self._url @property 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}') else: 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}') else: if 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)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/asset.py
asset.py
from __future__ import annotations from typing import List, Tuple, TypedDict, Any, TYPE_CHECKING, Callable, TypeVar, Literal, Optional, overload import array import ctypes import ctypes.util import logging import math import os.path import struct import sys from .errors import DiscordException, InvalidArgument if TYPE_CHECKING: T = TypeVar('T') BAND_CTL = Literal['narrow', 'medium', 'wide', 'superwide', 'full'] SIGNAL_CTL = Literal['auto', 'voice', 'music'] class BandCtl(TypedDict): narrow: int medium: int wide: int superwide: int full: int class SignalCtl(TypedDict): auto: int voice: int music: int __all__ = ( 'Encoder', 'OpusError', 'OpusNotLoaded', ) _log = logging.getLogger(__name__) c_int_ptr = ctypes.POINTER(ctypes.c_int) c_int16_ptr = ctypes.POINTER(ctypes.c_int16) c_float_ptr = ctypes.POINTER(ctypes.c_float) _lib = None class EncoderStruct(ctypes.Structure): pass class DecoderStruct(ctypes.Structure): pass EncoderStructPtr = ctypes.POINTER(EncoderStruct) DecoderStructPtr = ctypes.POINTER(DecoderStruct) ## Some constants from opus_defines.h # Error codes OK = 0 BAD_ARG = -1 # Encoder CTLs APPLICATION_AUDIO = 2049 APPLICATION_VOIP = 2048 APPLICATION_LOWDELAY = 2051 CTL_SET_BITRATE = 4002 CTL_SET_BANDWIDTH = 4008 CTL_SET_FEC = 4012 CTL_SET_PLP = 4014 CTL_SET_SIGNAL = 4024 # Decoder CTLs CTL_SET_GAIN = 4034 CTL_LAST_PACKET_DURATION = 4039 band_ctl: BandCtl = { 'narrow': 1101, 'medium': 1102, 'wide': 1103, 'superwide': 1104, 'full': 1105, } signal_ctl: SignalCtl = { 'auto': -1000, 'voice': 3001, 'music': 3002, } 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 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 # A list of exported functions. # The first argument is obviously the name. # The second one are the types of arguments it takes. # The third is the result type. # The fourth is the error handler. exported_functions: List[Tuple[Any, ...]] = [ # Generic ('opus_get_version_string', None, ctypes.c_char_p, None), ('opus_strerror', [ctypes.c_int], ctypes.c_char_p, None), # Encoder functions ('opus_encoder_get_size', [ctypes.c_int], ctypes.c_int, None), ('opus_encoder_create', [ctypes.c_int, ctypes.c_int, ctypes.c_int, c_int_ptr], EncoderStructPtr, _err_ne), ('opus_encode', [EncoderStructPtr, c_int16_ptr, ctypes.c_int, ctypes.c_char_p, ctypes.c_int32], ctypes.c_int32, _err_lt), ('opus_encode_float', [EncoderStructPtr, c_float_ptr, ctypes.c_int, ctypes.c_char_p, ctypes.c_int32], ctypes.c_int32, _err_lt), ('opus_encoder_ctl', None, ctypes.c_int32, _err_lt), ('opus_encoder_destroy', [EncoderStructPtr], None, None), # Decoder functions ('opus_decoder_get_size', [ctypes.c_int], ctypes.c_int, None), ('opus_decoder_create', [ctypes.c_int, ctypes.c_int, c_int_ptr], DecoderStructPtr, _err_ne), ('opus_decode', [DecoderStructPtr, ctypes.c_char_p, ctypes.c_int32, c_int16_ptr, ctypes.c_int, ctypes.c_int], ctypes.c_int, _err_lt), ('opus_decode_float', [DecoderStructPtr, ctypes.c_char_p, ctypes.c_int32, c_float_ptr, ctypes.c_int, ctypes.c_int], ctypes.c_int, _err_lt), ('opus_decoder_ctl', None, ctypes.c_int32, _err_lt), ('opus_decoder_destroy', [DecoderStructPtr], None, None), ('opus_decoder_get_nb_samples', [DecoderStructPtr, ctypes.c_char_p, ctypes.c_int32], ctypes.c_int, _err_lt), # Packet functions ('opus_packet_get_bandwidth', [ctypes.c_char_p], ctypes.c_int, _err_lt), ('opus_packet_get_nb_channels', [ctypes.c_char_p], ctypes.c_int, _err_lt), ('opus_packet_get_nb_frames', [ctypes.c_char_p, ctypes.c_int], ctypes.c_int, _err_lt), ('opus_packet_get_samples_per_frame', [ctypes.c_char_p, ctypes.c_int], ctypes.c_int, _err_lt), ] 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 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: _lib = libopus_loader(ctypes.util.find_library('opus')) except Exception: _lib = None return _lib is not None 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) 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. """ global _lib return _lib is not None 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): self.code: int = code msg = _lib.opus_strerror(self.code).decode('utf-8') _log.info('"%s" has happened', msg) super().__init__(msg) class OpusNotLoaded(DiscordException): """An exception that is thrown for when libopus is not loaded.""" pass class _OpusStruct: SAMPLING_RATE = 48000 CHANNELS = 2 FRAME_LENGTH = 20 # in milliseconds SAMPLE_SIZE = struct.calcsize('h') * CHANNELS SAMPLES_PER_FRAME = int(SAMPLING_RATE / 1000 * FRAME_LENGTH) FRAME_SIZE = SAMPLES_PER_FRAME * SAMPLE_SIZE @staticmethod def get_opus_version() -> str: if not is_loaded() and not _load_default(): raise OpusNotLoaded() return _lib.opus_get_version_string().decode('utf-8') class Encoder(_OpusStruct): def __init__(self, application: int = APPLICATION_AUDIO): _OpusStruct.get_opus_version() self.application: int = application self._state: EncoderStruct = self._create_state() self.set_bitrate(128) self.set_fec(True) self.set_expected_packet_loss_percent(0.15) self.set_bandwidth('full') self.set_signal_type('auto') def __del__(self) -> None: if hasattr(self, '_state'): _lib.opus_encoder_destroy(self._state) # This is a destructor, so it's okay to assign None self._state = None # type: ignore def _create_state(self) -> EncoderStruct: ret = ctypes.c_int() return _lib.opus_encoder_create(self.SAMPLING_RATE, self.CHANNELS, self.application, ctypes.byref(ret)) def set_bitrate(self, kbps: int) -> int: kbps = min(512, max(16, int(kbps))) _lib.opus_encoder_ctl(self._state, CTL_SET_BITRATE, kbps * 1024) return kbps def set_bandwidth(self, req: BAND_CTL) -> None: if req not in band_ctl: raise KeyError(f'{req!r} is not a valid bandwidth setting. Try one of: {",".join(band_ctl)}') k = band_ctl[req] _lib.opus_encoder_ctl(self._state, CTL_SET_BANDWIDTH, k) def set_signal_type(self, req: SIGNAL_CTL) -> None: if req not in signal_ctl: raise KeyError(f'{req!r} is not a valid bandwidth setting. Try one of: {",".join(signal_ctl)}') k = signal_ctl[req] _lib.opus_encoder_ctl(self._state, CTL_SET_SIGNAL, k) def set_fec(self, enabled: bool = True) -> None: _lib.opus_encoder_ctl(self._state, CTL_SET_FEC, 1 if enabled else 0) def set_expected_packet_loss_percent(self, percentage: float) -> None: _lib.opus_encoder_ctl(self._state, CTL_SET_PLP, min(100, max(0, int(percentage * 100)))) # type: ignore def encode(self, pcm: bytes, frame_size: int) -> bytes: max_data_bytes = len(pcm) # bytes can be used to reference pointer pcm_ptr = ctypes.cast(pcm, c_int16_ptr) # type: ignore data = (ctypes.c_char * max_data_bytes)() ret = _lib.opus_encode(self._state, pcm_ptr, frame_size, data, max_data_bytes) # array can be initialized with bytes but mypy doesn't know return array.array('b', data[:ret]).tobytes() # type: ignore class Decoder(_OpusStruct): def __init__(self): _OpusStruct.get_opus_version() self._state: DecoderStruct = self._create_state() def __del__(self) -> None: if hasattr(self, '_state'): _lib.opus_decoder_destroy(self._state) # This is a destructor, so it's okay to assign None self._state = None # type: ignore def _create_state(self) -> DecoderStruct: ret = ctypes.c_int() return _lib.opus_decoder_create(self.SAMPLING_RATE, self.CHANNELS, ctypes.byref(ret)) @staticmethod def packet_get_nb_frames(data: bytes) -> int: """Gets the number of frames in an Opus packet""" return _lib.opus_packet_get_nb_frames(data, len(data)) @staticmethod def packet_get_nb_channels(data: bytes) -> int: """Gets the number of channels in an Opus packet""" return _lib.opus_packet_get_nb_channels(data) @classmethod def packet_get_samples_per_frame(cls, data: bytes) -> int: """Gets the number of samples per frame from an Opus packet""" return _lib.opus_packet_get_samples_per_frame(data, cls.SAMPLING_RATE) def _set_gain(self, adjustment: int) -> int: """Configures decoder gain adjustment. Scales the decoded output by a factor specified in Q8 dB units. This has a maximum range of -32768 to 32767 inclusive, and returns OPUS_BAD_ARG (-1) otherwise. The default is zero indicating no adjustment. This setting survives decoder reset (irrelevant for now). gain = 10**x/(20.0*256) (from opus_defines.h) """ return _lib.opus_decoder_ctl(self._state, CTL_SET_GAIN, adjustment) def set_gain(self, dB: float) -> int: """Sets the decoder gain in dB, from -128 to 128.""" dB_Q8 = max(-32768, min(32767, round(dB * 256))) # dB * 2^n where n is 8 (Q8) return self._set_gain(dB_Q8) def set_volume(self, mult: float) -> int: """Sets the output volume as a float percent, i.e. 0.5 for 50%, 1.75 for 175%, etc.""" return self.set_gain(20 * math.log10(mult)) # amplitude ratio def _get_last_packet_duration(self) -> int: """Gets the duration (in samples) of the last packet successfully decoded or concealed.""" ret = ctypes.c_int32() _lib.opus_decoder_ctl(self._state, CTL_LAST_PACKET_DURATION, ctypes.byref(ret)) return ret.value @overload def decode(self, data: bytes, *, fec: bool) -> bytes: ... @overload def decode(self, data: Literal[None], *, fec: Literal[False]) -> bytes: ... def decode(self, data: Optional[bytes], *, fec: bool = False) -> bytes: if data is None and fec: raise InvalidArgument("Invalid arguments: FEC cannot be used with null data") if data is None: frame_size = self._get_last_packet_duration() or self.SAMPLES_PER_FRAME channel_count = self.CHANNELS else: frames = self.packet_get_nb_frames(data) channel_count = self.packet_get_nb_channels(data) samples_per_frame = self.packet_get_samples_per_frame(data) frame_size = frames * samples_per_frame pcm = (ctypes.c_int16 * (frame_size * channel_count))() pcm_ptr = ctypes.cast(pcm, c_int16_ptr) ret = _lib.opus_decode(self._state, data, len(data) if data else 0, pcm_ptr, frame_size, fec) return array.array('h', pcm[:ret * channel_count]).tobytes()
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/opus.py
opus.py
import argparse import sys from pathlib import Path import discord import pkg_resources import aiohttp import platform def show_version(): entries = [] entries.append('- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(sys.version_info)) version_info = discord.version_info entries.append('- discord.py v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info)) if version_info.releaselevel != 'final': pkg = pkg_resources.get_distribution('discord.py') if pkg: entries.append(f' - discord.py pkg_resources: v{pkg.version}') entries.append(f'- aiohttp v{aiohttp.__version__}') uname = platform.uname() entries.append('- system info: {0.system} {0.release} {0.version}'.format(uname)) print('\n'.join(entries)) def core(parser, args): if args.version: show_version() _bot_template = """#!/usr/bin/env python3 from discord.ext import commands import discord import config class Bot(commands.{base}): def __init__(self, **kwargs): super().__init__(command_prefix=commands.when_mentioned_or('{prefix}'), **kwargs) for cog in config.cogs: try: self.load_extension(cog) except Exception as exc: print(f'Could not load extension {{cog}} due to {{exc.__class__.__name__}}: {{exc}}') async def on_ready(self): print(f'Logged on as {{self.user}} (ID: {{self.user.id}})') bot = Bot() # write general commands here bot.run(config.token) """ _gitignore_template = """# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # Our configuration files config.py """ _cog_template = '''from discord.ext import commands import discord class {name}(commands.Cog{attrs}): """The description for {name} goes here.""" def __init__(self, bot): self.bot = bot {extra} def setup(bot): bot.add_cog({name}(bot)) ''' _cog_extras = ''' def cog_unload(self): # clean up logic goes here pass async def cog_check(self, ctx): # checks that apply to every command in here return True async def bot_check(self, ctx): # checks that apply to every command to the bot return True async def bot_check_once(self, ctx): # check that apply to every command but is guaranteed to be called only once return True async def cog_command_error(self, ctx, error): # error handling to every command in here pass async def cog_before_invoke(self, ctx): # called before a command is called here pass async def cog_after_invoke(self, ctx): # called after a command is called here pass ''' # certain file names and directory names are forbidden # see: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx # although some of this doesn't apply to Linux, we might as well be consistent _base_table = { '<': '-', '>': '-', ':': '-', '"': '-', # '/': '-', these are fine # '\\': '-', '|': '-', '?': '-', '*': '-', } # NUL (0) and 1-31 are disallowed _base_table.update((chr(i), None) for i in range(32)) _translation_table = str.maketrans(_base_table) def to_path(parser, name, *, replace_spaces=False): if isinstance(name, Path): return name if sys.platform == 'win32': forbidden = ('CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', \ 'COM8', 'COM9', 'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9') if len(name) <= 4 and name.upper() in forbidden: parser.error('invalid directory name given, use a different one') name = name.translate(_translation_table) if replace_spaces: name = name.replace(' ', '-') return Path(name) def newbot(parser, args): new_directory = to_path(parser, args.directory) / to_path(parser, args.name) # as a note exist_ok for Path is a 3.5+ only feature # since we already checked above that we're >3.5 try: new_directory.mkdir(exist_ok=True, parents=True) except OSError as exc: parser.error(f'could not create our bot directory ({exc})') cogs = new_directory / 'cogs' try: cogs.mkdir(exist_ok=True) init = cogs / '__init__.py' init.touch() except OSError as exc: print(f'warning: could not create cogs directory ({exc})') try: with open(str(new_directory / 'config.py'), 'w', encoding='utf-8') as fp: fp.write('token = "place your token here"\ncogs = []\n') except OSError as exc: parser.error(f'could not create config file ({exc})') try: with open(str(new_directory / 'bot.py'), 'w', encoding='utf-8') as fp: base = 'Bot' if not args.sharded else 'AutoShardedBot' fp.write(_bot_template.format(base=base, prefix=args.prefix)) except OSError as exc: parser.error(f'could not create bot file ({exc})') if not args.no_git: try: with open(str(new_directory / '.gitignore'), 'w', encoding='utf-8') as fp: fp.write(_gitignore_template) except OSError as exc: print(f'warning: could not create .gitignore file ({exc})') print('successfully made bot at', new_directory) def newcog(parser, args): cog_dir = to_path(parser, args.directory) try: cog_dir.mkdir(exist_ok=True) except OSError as exc: print(f'warning: could not create cogs directory ({exc})') directory = cog_dir / to_path(parser, args.name) directory = directory.with_suffix('.py') try: with open(str(directory), 'w', encoding='utf-8') as fp: attrs = '' extra = _cog_extras if args.full else '' if args.class_name: name = args.class_name else: name = str(directory.stem) if '-' in name or '_' in name: translation = str.maketrans('-_', ' ') name = name.translate(translation).title().replace(' ', '') else: name = name.title() if args.display_name: attrs += f', name="{args.display_name}"' if args.hide_commands: attrs += ', command_attrs=dict(hidden=True)' fp.write(_cog_template.format(name=name, extra=extra, attrs=attrs)) except OSError as exc: parser.error(f'could not create cog file ({exc})') else: print('successfully made cog at', directory) def add_newbot_args(subparser): 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): 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 discord.py') 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() def main(): parser, args = parse_args() args.func(parser, args) if __name__ == '__main__': main()
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/__main__.py
__main__.py
from __future__ import annotations import datetime from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union, overload from .asset import Asset from .enums import ActivityType, try_enum from .colour import Colour from .partial_emoji import PartialEmoji from .utils import _get_as_snowflake __all__ = ( 'BaseActivity', 'Activity', 'Streaming', 'Game', 'Spotify', 'CustomActivity', ) """If curious, this is the current schema for an activity. It's fairly long so I will document it here: All keys are optional. state: str (max: 128), details: str (max: 128) timestamps: dict start: int (min: 1) end: int (min: 1) assets: dict large_image: str (max: 32) large_text: str (max: 128) small_image: str (max: 32) small_text: str (max: 128) party: dict id: str (max: 128), size: List[int] (max-length: 2) elem: int (min: 1) secrets: dict match: str (max: 128) join: str (max: 128) spectate: str (max: 128) instance: bool application_id: str name: str (max: 128) url: str type: int sync_id: str session_id: str flags: int buttons: list[dict] label: str (max: 32) url: str (max: 512) There are also activity flags which are mostly uninteresting for the library atm. t.ActivityFlags = { INSTANCE: 1, JOIN: 2, SPECTATE: 4, JOIN_REQUEST: 8, SYNC: 16, PLAY: 32 } """ if TYPE_CHECKING: from .types.activity import ( Activity as ActivityPayload, ActivityTimestamps, ActivityParty, ActivityAssets, ActivityButton, ) class BaseActivity: """The base activity that all user-settable activities inherit from. A user-settable activity is one that can be used in :meth:`Client.change_presence`. The following types currently count as user-settable: - :class:`Activity` - :class:`Game` - :class:`Streaming` - :class:`CustomActivity` Note that although these types are considered user-settable by the library, Discord typically ignores certain combinations of activity depending on what is currently set. This behaviour may change in the future so there are no guarantees on whether Discord will actually let you set these types. .. versionadded:: 1.3 """ __slots__ = ('_created_at',) def __init__(self, **kwargs): self._created_at: Optional[float] = kwargs.pop('created_at', None) @property def created_at(self) -> Optional[datetime.datetime]: """Optional[:class:`datetime.datetime`]: When the user started doing this activity in UTC. .. versionadded:: 1.3 """ if self._created_at is not None: return datetime.datetime.fromtimestamp(self._created_at / 1000, tz=datetime.timezone.utc) def to_dict(self) -> ActivityPayload: raise NotImplementedError class Activity(BaseActivity): """Represents an activity in Discord. This could be an activity such as streaming, playing, listening or watching. For memory optimisation purposes, some activities are offered in slimmed down versions: - :class:`Game` - :class:`Streaming` Attributes ------------ application_id: Optional[:class:`int`] The application ID of the game. name: Optional[:class:`str`] The name of the activity. url: Optional[:class:`str`] A stream URL that the activity could be doing. type: :class:`ActivityType` The type of activity currently being done. state: Optional[:class:`str`] The user's current state. For example, "In Game". details: Optional[:class:`str`] The detail of the user's current activity. timestamps: :class:`dict` A dictionary of timestamps. It contains the following optional keys: - ``start``: Corresponds to when the user started doing the activity in milliseconds since Unix epoch. - ``end``: Corresponds to when the user will finish doing the activity in milliseconds since Unix epoch. assets: :class:`dict` A dictionary representing the images and their hover text of an activity. It contains the following optional keys: - ``large_image``: A string representing the ID for the large image asset. - ``large_text``: A string representing the text when hovering over the large image asset. - ``small_image``: A string representing the ID for the small image asset. - ``small_text``: A string representing the text when hovering over the small image asset. party: :class:`dict` A dictionary representing the activity party. It contains the following optional keys: - ``id``: A string representing the party ID. - ``size``: A list of up to two integer elements denoting (current_size, maximum_size). buttons: List[:class:`dict`] An list of dictionaries representing custom buttons shown in a rich presence. Each dictionary contains the following keys: - ``label``: A string representing the text shown on the button. - ``url``: A string representing the URL opened upon clicking the button. .. versionadded:: 2.0 emoji: Optional[:class:`PartialEmoji`] The emoji that belongs to this activity. """ __slots__ = ( 'state', 'details', '_created_at', 'timestamps', 'assets', 'party', 'flags', 'sync_id', 'session_id', 'type', 'name', 'url', 'application_id', 'emoji', 'buttons', ) def __init__(self, **kwargs): super().__init__(**kwargs) self.state: Optional[str] = kwargs.pop('state', None) self.details: Optional[str] = kwargs.pop('details', None) self.timestamps: ActivityTimestamps = kwargs.pop('timestamps', {}) self.assets: ActivityAssets = kwargs.pop('assets', {}) self.party: ActivityParty = kwargs.pop('party', {}) self.application_id: Optional[int] = _get_as_snowflake(kwargs, 'application_id') self.name: Optional[str] = kwargs.pop('name', None) self.url: Optional[str] = kwargs.pop('url', None) self.flags: int = kwargs.pop('flags', 0) self.sync_id: Optional[str] = kwargs.pop('sync_id', None) self.session_id: Optional[str] = kwargs.pop('session_id', None) self.buttons: List[ActivityButton] = kwargs.pop('buttons', []) activity_type = kwargs.pop('type', -1) self.type: ActivityType = ( activity_type if isinstance(activity_type, ActivityType) else try_enum(ActivityType, activity_type) ) emoji = kwargs.pop('emoji', None) self.emoji: Optional[PartialEmoji] = PartialEmoji.from_dict(emoji) if emoji is not None else None def __repr__(self) -> str: attrs = ( ('type', self.type), ('name', self.name), ('url', self.url), ('details', self.details), ('application_id', self.application_id), ('session_id', self.session_id), ('emoji', self.emoji), ) inner = ' '.join('%s=%r' % t for t in attrs) return f'<Activity {inner}>' def to_dict(self) -> Dict[str, Any]: ret: Dict[str, Any] = {} for attr in self.__slots__: value = getattr(self, attr, None) if value is None: continue if isinstance(value, dict) and len(value) == 0: continue ret[attr] = value ret['type'] = int(self.type) if self.emoji: ret['emoji'] = self.emoji.to_dict() return ret @property def start(self) -> Optional[datetime.datetime]: """Optional[:class:`datetime.datetime`]: When the user started doing this activity in UTC, if applicable.""" try: timestamp = self.timestamps['start'] / 1000 except KeyError: return None else: return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc) @property def end(self) -> Optional[datetime.datetime]: """Optional[:class:`datetime.datetime`]: When the user will stop doing this activity in UTC, if applicable.""" try: timestamp = self.timestamps['end'] / 1000 except KeyError: return None else: return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc) @property def large_image_url(self) -> Optional[str]: """Optional[:class:`str`]: Returns a URL pointing to the large image asset of this activity if applicable.""" if self.application_id is None: return None try: large_image = self.assets['large_image'] except KeyError: return None else: return Asset.BASE + f'/app-assets/{self.application_id}/{large_image}.png' @property def small_image_url(self) -> Optional[str]: """Optional[:class:`str`]: Returns a URL pointing to the small image asset of this activity if applicable.""" if self.application_id is None: return None try: small_image = self.assets['small_image'] except KeyError: return None else: return Asset.BASE + f'/app-assets/{self.application_id}/{small_image}.png' @property def large_image_text(self) -> Optional[str]: """Optional[:class:`str`]: Returns the large image asset hover text of this activity if applicable.""" return self.assets.get('large_text', None) @property def small_image_text(self) -> Optional[str]: """Optional[:class:`str`]: Returns the small image asset hover text of this activity if applicable.""" return self.assets.get('small_text', None) class Game(BaseActivity): """A slimmed down version of :class:`Activity` that represents a Discord game. This is typically displayed via **Playing** on the official Discord client. .. container:: operations .. describe:: x == y Checks if two games are equal. .. describe:: x != y Checks if two games are not equal. .. describe:: hash(x) Returns the game's hash. .. describe:: str(x) Returns the game's name. Parameters ----------- name: :class:`str` The game's name. Attributes ----------- name: :class:`str` The game's name. """ __slots__ = ('name', '_end', '_start') def __init__(self, name: str, **extra): super().__init__(**extra) self.name: str = name try: timestamps: ActivityTimestamps = extra['timestamps'] except KeyError: self._start = 0 self._end = 0 else: self._start = timestamps.get('start', 0) self._end = timestamps.get('end', 0) @property def type(self) -> ActivityType: """:class:`ActivityType`: Returns the game's type. This is for compatibility with :class:`Activity`. It always returns :attr:`ActivityType.playing`. """ return ActivityType.playing @property def start(self) -> Optional[datetime.datetime]: """Optional[:class:`datetime.datetime`]: When the user started playing this game in UTC, if applicable.""" if self._start: return datetime.datetime.fromtimestamp(self._start / 1000, tz=datetime.timezone.utc) return None @property def end(self) -> Optional[datetime.datetime]: """Optional[:class:`datetime.datetime`]: When the user will stop playing this game in UTC, if applicable.""" if self._end: return datetime.datetime.fromtimestamp(self._end / 1000, tz=datetime.timezone.utc) return None def __str__(self) -> str: return str(self.name) def __repr__(self) -> str: return f'<Game name={self.name!r}>' def to_dict(self) -> Dict[str, Any]: timestamps: Dict[str, Any] = {} if self._start: timestamps['start'] = self._start if self._end: timestamps['end'] = self._end # fmt: off return { 'type': ActivityType.playing.value, 'name': str(self.name), 'timestamps': timestamps } # fmt: on def __eq__(self, other: Any) -> bool: return isinstance(other, Game) and other.name == self.name def __ne__(self, other: Any) -> bool: return not self.__eq__(other) def __hash__(self) -> int: return hash(self.name) class Streaming(BaseActivity): """A slimmed down version of :class:`Activity` that represents a Discord streaming status. This is typically displayed via **Streaming** on the official Discord client. .. container:: operations .. describe:: x == y Checks if two streams are equal. .. describe:: x != y Checks if two streams are not equal. .. describe:: hash(x) Returns the stream's hash. .. describe:: str(x) Returns the stream's name. Attributes ----------- platform: Optional[:class:`str`] Where the user is streaming from (ie. YouTube, Twitch). .. versionadded:: 1.3 name: Optional[:class:`str`] The stream's name. details: Optional[:class:`str`] An alias for :attr:`name` game: Optional[:class:`str`] The game being streamed. .. versionadded:: 1.3 url: :class:`str` The stream's URL. assets: :class:`dict` A dictionary comprising of similar keys than those in :attr:`Activity.assets`. """ __slots__ = ('platform', 'name', 'game', 'url', 'details', 'assets') def __init__(self, *, name: Optional[str], url: str, **extra: Any): super().__init__(**extra) self.platform: Optional[str] = name self.name: Optional[str] = extra.pop('details', name) self.game: Optional[str] = extra.pop('state', None) self.url: str = url self.details: Optional[str] = extra.pop('details', self.name) # compatibility self.assets: ActivityAssets = extra.pop('assets', {}) @property def type(self) -> ActivityType: """:class:`ActivityType`: Returns the game's type. This is for compatibility with :class:`Activity`. It always returns :attr:`ActivityType.streaming`. """ return ActivityType.streaming def __str__(self) -> str: return str(self.name) def __repr__(self) -> str: return f'<Streaming name={self.name!r}>' @property def twitch_name(self): """Optional[:class:`str`]: If provided, the twitch name of the user streaming. This corresponds to the ``large_image`` key of the :attr:`Streaming.assets` dictionary if it starts with ``twitch:``. Typically set by the Discord client. """ try: name = self.assets['large_image'] except KeyError: return None else: return name[7:] if name[:7] == 'twitch:' else None def to_dict(self) -> Dict[str, Any]: # fmt: off ret: Dict[str, Any] = { 'type': ActivityType.streaming.value, 'name': str(self.name), 'url': str(self.url), 'assets': self.assets } # fmt: on if self.details: ret['details'] = self.details return ret def __eq__(self, other: Any) -> bool: return isinstance(other, Streaming) and other.name == self.name and other.url == self.url def __ne__(self, other: Any) -> bool: return not self.__eq__(other) def __hash__(self) -> int: return hash(self.name) class Spotify: """Represents a Spotify listening activity from Discord. This is a special case of :class:`Activity` that makes it easier to work with the Spotify integration. .. container:: operations .. describe:: x == y Checks if two activities are equal. .. describe:: x != y Checks if two activities are not equal. .. describe:: hash(x) Returns the activity's hash. .. describe:: str(x) Returns the string 'Spotify'. """ __slots__ = ('_state', '_details', '_timestamps', '_assets', '_party', '_sync_id', '_session_id', '_created_at') def __init__(self, **data): self._state: str = data.pop('state', '') self._details: str = data.pop('details', '') self._timestamps: Dict[str, int] = data.pop('timestamps', {}) self._assets: ActivityAssets = data.pop('assets', {}) self._party: ActivityParty = data.pop('party', {}) self._sync_id: str = data.pop('sync_id') self._session_id: str = data.pop('session_id') self._created_at: Optional[float] = data.pop('created_at', None) @property def type(self) -> ActivityType: """:class:`ActivityType`: Returns the activity's type. This is for compatibility with :class:`Activity`. It always returns :attr:`ActivityType.listening`. """ return ActivityType.listening @property def created_at(self) -> Optional[datetime.datetime]: """Optional[:class:`datetime.datetime`]: When the user started listening in UTC. .. versionadded:: 1.3 """ if self._created_at is not None: return datetime.datetime.fromtimestamp(self._created_at / 1000, tz=datetime.timezone.utc) @property def colour(self) -> Colour: """:class:`Colour`: Returns the Spotify integration colour, as a :class:`Colour`. There is an alias for this named :attr:`color`""" return Colour(0x1DB954) @property def color(self) -> Colour: """:class:`Colour`: Returns the Spotify integration colour, as a :class:`Colour`. There is an alias for this named :attr:`colour`""" return self.colour def to_dict(self) -> Dict[str, Any]: return { 'flags': 48, # SYNC | PLAY 'name': 'Spotify', 'assets': self._assets, 'party': self._party, 'sync_id': self._sync_id, 'session_id': self._session_id, 'timestamps': self._timestamps, 'details': self._details, 'state': self._state, } @property def name(self) -> str: """:class:`str`: The activity's name. This will always return "Spotify".""" return 'Spotify' def __eq__(self, other: Any) -> bool: return ( isinstance(other, Spotify) and other._session_id == self._session_id and other._sync_id == self._sync_id and other.start == self.start ) def __ne__(self, other: Any) -> bool: return not self.__eq__(other) def __hash__(self) -> int: return hash(self._session_id) def __str__(self) -> str: return 'Spotify' def __repr__(self) -> str: return f'<Spotify title={self.title!r} artist={self.artist!r} track_id={self.track_id!r}>' @property def title(self) -> str: """:class:`str`: The title of the song being played.""" return self._details @property def artists(self) -> List[str]: """List[:class:`str`]: The artists of the song being played.""" return self._state.split('; ') @property def artist(self) -> str: """:class:`str`: The artist of the song being played. This does not attempt to split the artist information into multiple artists. Useful if there's only a single artist. """ return self._state @property def album(self) -> str: """:class:`str`: The album that the song being played belongs to.""" return self._assets.get('large_text', '') @property def album_cover_url(self) -> str: """:class:`str`: The album cover image URL from Spotify's CDN.""" large_image = self._assets.get('large_image', '') if large_image[:8] != 'spotify:': return '' album_image_id = large_image[8:] return 'https://i.scdn.co/image/' + album_image_id @property def track_id(self) -> str: """:class:`str`: The track ID used by Spotify to identify this song.""" return self._sync_id @property def track_url(self) -> str: """:class:`str`: The track URL to listen on Spotify. .. versionadded:: 2.0 """ return f'https://open.spotify.com/track/{self.track_id}' @property def start(self) -> datetime.datetime: """:class:`datetime.datetime`: When the user started playing this song in UTC.""" return datetime.datetime.fromtimestamp(self._timestamps['start'] / 1000, tz=datetime.timezone.utc) @property def end(self) -> datetime.datetime: """:class:`datetime.datetime`: When the user will stop playing this song in UTC.""" return datetime.datetime.fromtimestamp(self._timestamps['end'] / 1000, tz=datetime.timezone.utc) @property def duration(self) -> datetime.timedelta: """:class:`datetime.timedelta`: The duration of the song being played.""" return self.end - self.start @property def party_id(self) -> str: """:class:`str`: The party ID of the listening party.""" return self._party.get('id', '') class CustomActivity(BaseActivity): """Represents a Custom activity from Discord. .. container:: operations .. describe:: x == y Checks if two activities are equal. .. describe:: x != y Checks if two activities are not equal. .. describe:: hash(x) Returns the activity's hash. .. describe:: str(x) Returns the custom status text. .. versionadded:: 1.3 Attributes ----------- name: Optional[:class:`str`] The custom activity's name. emoji: Optional[:class:`PartialEmoji`] The emoji to pass to the activity, if any. """ __slots__ = ('name', 'emoji', 'state') def __init__(self, name: Optional[str], *, emoji: Optional[PartialEmoji] = None, **extra: Any): super().__init__(**extra) self.name: Optional[str] = name self.state: Optional[str] = extra.pop('state', None) if self.name == 'Custom Status': self.name = self.state self.emoji: Optional[PartialEmoji] if emoji is None: self.emoji = emoji elif isinstance(emoji, dict): self.emoji = PartialEmoji.from_dict(emoji) elif isinstance(emoji, str): self.emoji = PartialEmoji(name=emoji) elif isinstance(emoji, PartialEmoji): self.emoji = emoji else: raise TypeError(f'Expected str, PartialEmoji, or None, received {type(emoji)!r} instead.') @property def type(self) -> ActivityType: """:class:`ActivityType`: Returns the activity's type. This is for compatibility with :class:`Activity`. It always returns :attr:`ActivityType.custom`. """ return ActivityType.custom def to_dict(self) -> Dict[str, Any]: if self.name == self.state: o = { 'type': ActivityType.custom.value, 'state': self.name, 'name': 'Custom Status', } else: o = { 'type': ActivityType.custom.value, 'name': self.name, } if self.emoji: o['emoji'] = self.emoji.to_dict() return o def __eq__(self, other: Any) -> bool: return isinstance(other, CustomActivity) and other.name == self.name and other.emoji == self.emoji def __ne__(self, other: Any) -> bool: return not self.__eq__(other) def __hash__(self) -> int: return hash((self.name, str(self.emoji))) def __str__(self) -> str: if self.emoji: if self.name: return f'{self.emoji} {self.name}' return str(self.emoji) else: return str(self.name) def __repr__(self) -> str: return f'<CustomActivity name={self.name!r} emoji={self.emoji!r}>' ActivityTypes = Union[Activity, Game, CustomActivity, Streaming, Spotify] @overload def create_activity(data: ActivityPayload) -> ActivityTypes: ... @overload def create_activity(data: None) -> None: ... def create_activity(data: Optional[ActivityPayload]) -> Optional[ActivityTypes]: if not data: return None game_type = try_enum(ActivityType, data.get('type', -1)) if game_type is ActivityType.playing: if 'application_id' in data or 'session_id' in data: return Activity(**data) return Game(**data) elif game_type is ActivityType.custom: try: name = data.pop('name') except KeyError: return Activity(**data) else: # we removed the name key from data already return CustomActivity(name=name, **data) # type: ignore elif game_type is ActivityType.streaming: if 'url' in data: # the url won't be None here return Streaming(**data) # type: ignore return Activity(**data) elif game_type is ActivityType.listening and 'sync_id' in data and 'session_id' in data: return Spotify(**data) return Activity(**data)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/activity.py
activity.py
from __future__ import annotations import threading import traceback import subprocess import audioop import asyncio import logging import shlex import time import json import sys import re import io from typing import Any, Callable, Generic, IO, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Union from .errors import ClientException from .opus import Encoder as OpusEncoder from .oggparse import OggStream from .utils import MISSING if TYPE_CHECKING: from .voice_client import VoiceClient AT = TypeVar('AT', bound='AudioSource') FT = TypeVar('FT', bound='FFmpegOpusAudio') _log = logging.getLogger(__name__) __all__ = ( 'AudioSource', 'PCMAudio', 'FFmpegAudio', 'FFmpegPCMAudio', 'FFmpegOpusAudio', 'PCMVolumeTransformer', ) CREATE_NO_WINDOW: int if sys.platform != 'win32': CREATE_NO_WINDOW = 0 else: CREATE_NO_WINDOW = 0x08000000 class AudioSource: """Represents an audio stream. The audio stream can be Opus encoded or not, however if the audio stream is not Opus encoded then the audio format must be 16-bit 48KHz stereo PCM. .. warning:: The audio source reads are done in a separate thread. """ def read(self) -> bytes: """Reads 20ms worth of audio. Subclasses must implement this. If the audio is complete, then returning an empty :term:`py:bytes-like object` to signal this is the way to do so. If :meth:`~AudioSource.is_opus` method returns ``True``, then it must return 20ms worth of Opus encoded audio. Otherwise, it must be 20ms worth of 16-bit 48KHz stereo PCM, which is about 3,840 bytes per frame (20ms worth of audio). Returns -------- :class:`bytes` A bytes like object that represents the PCM or Opus data. """ raise NotImplementedError def is_opus(self) -> bool: """Checks if the audio source is already encoded in Opus.""" return False def cleanup(self) -> None: """Called when clean-up is needed to be done. Useful for clearing buffer data or processes after it is done playing audio. """ pass def __del__(self) -> None: self.cleanup() class PCMAudio(AudioSource): """Represents raw 16-bit 48KHz stereo PCM audio source. Attributes ----------- stream: :term:`py:file object` A file-like object that reads byte data representing raw PCM. """ def __init__(self, stream: io.BufferedIOBase) -> None: self.stream: io.BufferedIOBase = stream def read(self) -> bytes: ret = self.stream.read(OpusEncoder.FRAME_SIZE) if len(ret) != OpusEncoder.FRAME_SIZE: return b'' return ret class FFmpegAudio(AudioSource): """Represents an FFmpeg (or AVConv) based AudioSource. User created AudioSources using FFmpeg differently from how :class:`FFmpegPCMAudio` and :class:`FFmpegOpusAudio` work should subclass this. .. versionadded:: 1.3 """ def __init__(self, source: Union[str, io.BufferedIOBase], *, executable: str = 'ffmpeg', args: Any, **subprocess_kwargs: Any): piping = subprocess_kwargs.get('stdin') == subprocess.PIPE if piping and isinstance(source, str): raise TypeError("parameter conflict: 'source' parameter cannot be a string when piping to stdin") args = [executable, *args] kwargs = {'stdout': subprocess.PIPE} kwargs.update(subprocess_kwargs) self._process: subprocess.Popen = self._spawn_process(args, **kwargs) self._stdout: IO[bytes] = self._process.stdout # type: ignore self._stdin: Optional[IO[Bytes]] = None self._pipe_thread: Optional[threading.Thread] = None if piping: n = f'popen-stdin-writer:{id(self):#x}' self._stdin = self._process.stdin self._pipe_thread = threading.Thread(target=self._pipe_writer, args=(source,), daemon=True, name=n) self._pipe_thread.start() def _spawn_process(self, args: Any, **subprocess_kwargs: Any) -> subprocess.Popen: process = None try: process = subprocess.Popen(args, creationflags=CREATE_NO_WINDOW, **subprocess_kwargs) except FileNotFoundError: executable = args.partition(' ')[0] if isinstance(args, str) else args[0] raise ClientException(executable + ' was not found.') from None except subprocess.SubprocessError as exc: raise ClientException(f'Popen failed: {exc.__class__.__name__}: {exc}') from exc else: return process def _kill_process(self) -> None: proc = self._process if proc is MISSING: return _log.info('Preparing to terminate ffmpeg process %s.', proc.pid) try: proc.kill() except Exception: _log.exception('Ignoring error attempting to kill ffmpeg process %s', proc.pid) if proc.poll() is None: _log.info('ffmpeg process %s has not terminated. Waiting to terminate...', proc.pid) proc.communicate() _log.info('ffmpeg process %s should have terminated with a return code of %s.', proc.pid, proc.returncode) else: _log.info('ffmpeg process %s successfully terminated with return code of %s.', proc.pid, proc.returncode) def _pipe_writer(self, source: io.BufferedIOBase) -> None: while self._process: # arbitrarily large read size data = source.read(8192) if not data: self._process.terminate() return try: self._stdin.write(data) except Exception: _log.debug('Write error for %s, this is probably not a problem', self, exc_info=True) # at this point the source data is either exhausted or the process is fubar self._process.terminate() return def cleanup(self) -> None: self._kill_process() self._process = self._stdout = self._stdin = MISSING class FFmpegPCMAudio(FFmpegAudio): """An audio source from FFmpeg (or AVConv). This launches a sub-process to a specific input file given. .. warning:: You must have the ffmpeg or avconv executable in your path environment variable in order for this to work. Parameters ------------ source: Union[:class:`str`, :class:`io.BufferedIOBase`] The input that ffmpeg will take and convert to PCM bytes. If ``pipe`` is ``True`` then this is a file-like object that is passed to the stdin of ffmpeg. executable: :class:`str` The executable name (and path) to use. Defaults to ``ffmpeg``. pipe: :class:`bool` If ``True``, denotes that ``source`` parameter will be passed to the stdin of ffmpeg. Defaults to ``False``. stderr: Optional[:term:`py:file object`] A file-like object to pass to the Popen constructor. Could also be an instance of ``subprocess.PIPE``. before_options: Optional[:class:`str`] Extra command line arguments to pass to ffmpeg before the ``-i`` flag. options: Optional[:class:`str`] Extra command line arguments to pass to ffmpeg after the ``-i`` flag. Raises -------- ClientException The subprocess failed to be created. """ def __init__( self, source: Union[str, io.BufferedIOBase], *, executable: str = 'ffmpeg', pipe: bool = False, stderr: Optional[IO[str]] = None, before_options: Optional[str] = None, options: Optional[str] = None ) -> None: args = [] subprocess_kwargs = {'stdin': subprocess.PIPE if pipe else subprocess.DEVNULL, 'stderr': stderr} if isinstance(before_options, str): args.extend(shlex.split(before_options)) args.append('-i') args.append('-' if pipe else source) args.extend(('-f', 's16le', '-ar', '48000', '-ac', '2', '-loglevel', 'warning')) if isinstance(options, str): args.extend(shlex.split(options)) args.append('pipe:1') super().__init__(source, executable=executable, args=args, **subprocess_kwargs) def read(self) -> bytes: ret = self._stdout.read(OpusEncoder.FRAME_SIZE) if len(ret) != OpusEncoder.FRAME_SIZE: return b'' return ret def is_opus(self) -> bool: return False class FFmpegOpusAudio(FFmpegAudio): """An audio source from FFmpeg (or AVConv). This launches a sub-process to a specific input file given. However, rather than producing PCM packets like :class:`FFmpegPCMAudio` does that need to be encoded to Opus, this class produces Opus packets, skipping the encoding step done by the library. Alternatively, instead of instantiating this class directly, you can use :meth:`FFmpegOpusAudio.from_probe` to probe for bitrate and codec information. This can be used to opportunistically skip pointless re-encoding of existing Opus audio data for a boost in performance at the cost of a short initial delay to gather the information. The same can be achieved by passing ``copy`` to the ``codec`` parameter, but only if you know that the input source is Opus encoded beforehand. .. versionadded:: 1.3 .. warning:: You must have the ffmpeg or avconv executable in your path environment variable in order for this to work. Parameters ------------ source: Union[:class:`str`, :class:`io.BufferedIOBase`] The input that ffmpeg will take and convert to Opus bytes. If ``pipe`` is ``True`` then this is a file-like object that is passed to the stdin of ffmpeg. bitrate: :class:`int` The bitrate in kbps to encode the output to. Defaults to ``128``. codec: Optional[:class:`str`] The codec to use to encode the audio data. Normally this would be just ``libopus``, but is used by :meth:`FFmpegOpusAudio.from_probe` to opportunistically skip pointlessly re-encoding Opus audio data by passing ``copy`` as the codec value. Any values other than ``copy``, ``opus``, or ``libopus`` will be considered ``libopus``. Defaults to ``libopus``. .. warning:: Do not provide this parameter unless you are certain that the audio input is already Opus encoded. For typical use :meth:`FFmpegOpusAudio.from_probe` should be used to determine the proper value for this parameter. executable: :class:`str` The executable name (and path) to use. Defaults to ``ffmpeg``. pipe: :class:`bool` If ``True``, denotes that ``source`` parameter will be passed to the stdin of ffmpeg. Defaults to ``False``. stderr: Optional[:term:`py:file object`] A file-like object to pass to the Popen constructor. Could also be an instance of ``subprocess.PIPE``. before_options: Optional[:class:`str`] Extra command line arguments to pass to ffmpeg before the ``-i`` flag. options: Optional[:class:`str`] Extra command line arguments to pass to ffmpeg after the ``-i`` flag. Raises -------- ClientException The subprocess failed to be created. """ def __init__( self, source: Union[str, io.BufferedIOBase], *, bitrate: int = 128, codec: Optional[str] = None, executable: str = 'ffmpeg', pipe=False, stderr=None, before_options=None, options=None, ) -> None: args = [] subprocess_kwargs = {'stdin': subprocess.PIPE if pipe else subprocess.DEVNULL, 'stderr': stderr} if isinstance(before_options, str): args.extend(shlex.split(before_options)) args.append('-i') args.append('-' if pipe else source) codec = 'copy' if codec in ('opus', 'libopus') else 'libopus' args.extend(('-map_metadata', '-1', '-f', 'opus', '-c:a', codec, '-ar', '48000', '-ac', '2', '-b:a', f'{bitrate}k', '-loglevel', 'warning')) if isinstance(options, str): args.extend(shlex.split(options)) args.append('pipe:1') super().__init__(source, executable=executable, args=args, **subprocess_kwargs) self._packet_iter = OggStream(self._stdout).iter_packets() @classmethod async def from_probe( cls: Type[FT], source: str, *, method: Optional[Union[str, Callable[[str, str], Tuple[Optional[str], Optional[int]]]]] = None, **kwargs: Any, ) -> FT: """|coro| A factory method that creates a :class:`FFmpegOpusAudio` after probing the input source for audio codec and bitrate information. Examples ---------- Use this function to create an :class:`FFmpegOpusAudio` instance instead of the constructor: :: source = await discord.FFmpegOpusAudio.from_probe("song.webm") voice_client.play(source) If you are on Windows and don't have ffprobe installed, use the ``fallback`` method to probe using ffmpeg instead: :: source = await discord.FFmpegOpusAudio.from_probe("song.webm", method='fallback') voice_client.play(source) Using a custom method of determining codec and bitrate: :: def custom_probe(source, executable): # some analysis code here return codec, bitrate source = await discord.FFmpegOpusAudio.from_probe("song.webm", method=custom_probe) voice_client.play(source) Parameters ------------ source Identical to the ``source`` parameter for the constructor. method: Optional[Union[:class:`str`, Callable[:class:`str`, :class:`str`]]] The probing method used to determine bitrate and codec information. As a string, valid values are ``native`` to use ffprobe (or avprobe) and ``fallback`` to use ffmpeg (or avconv). As a callable, it must take two string arguments, ``source`` and ``executable``. Both parameters are the same values passed to this factory function. ``executable`` will default to ``ffmpeg`` if not provided as a keyword argument. kwargs The remaining parameters to be passed to the :class:`FFmpegOpusAudio` constructor, excluding ``bitrate`` and ``codec``. Raises -------- AttributeError Invalid probe method, must be ``'native'`` or ``'fallback'``. TypeError Invalid value for ``probe`` parameter, must be :class:`str` or a callable. Returns -------- :class:`FFmpegOpusAudio` An instance of this class. """ executable = kwargs.get('executable') codec, bitrate = await cls.probe(source, method=method, executable=executable) return cls(source, bitrate=bitrate, codec=codec, **kwargs) # type: ignore @classmethod async def probe( cls, source: str, *, method: Optional[Union[str, Callable[[str, str], Tuple[Optional[str], Optional[int]]]]] = None, executable: Optional[str] = None, ) -> Tuple[Optional[str], Optional[int]]: """|coro| Probes the input source for bitrate and codec information. Parameters ------------ source Identical to the ``source`` parameter for :class:`FFmpegOpusAudio`. method Identical to the ``method`` parameter for :meth:`FFmpegOpusAudio.from_probe`. executable: :class:`str` Identical to the ``executable`` parameter for :class:`FFmpegOpusAudio`. Raises -------- AttributeError Invalid probe method, must be ``'native'`` or ``'fallback'``. TypeError Invalid value for ``probe`` parameter, must be :class:`str` or a callable. Returns --------- Optional[Tuple[Optional[:class:`str`], Optional[:class:`int`]]] A 2-tuple with the codec and bitrate of the input source. """ method = method or 'native' executable = executable or 'ffmpeg' probefunc = fallback = None if isinstance(method, str): probefunc = getattr(cls, '_probe_codec_' + method, None) if probefunc is None: raise AttributeError(f"Invalid probe method {method!r}") if probefunc is cls._probe_codec_native: fallback = cls._probe_codec_fallback elif callable(method): probefunc = method fallback = cls._probe_codec_fallback else: raise TypeError("Expected str or callable for parameter 'probe', " \ f"not '{method.__class__.__name__}'") codec = bitrate = None loop = asyncio.get_event_loop() try: codec, bitrate = await loop.run_in_executor(None, lambda: probefunc(source, executable)) # type: ignore except Exception: if not fallback: _log.exception("Probe '%s' using '%s' failed", method, executable) return # type: ignore _log.exception("Probe '%s' using '%s' failed, trying fallback", method, executable) try: codec, bitrate = await loop.run_in_executor(None, lambda: fallback(source, executable)) # type: ignore except Exception: _log.exception("Fallback probe using '%s' failed", executable) else: _log.info("Fallback probe found codec=%s, bitrate=%s", codec, bitrate) else: _log.info("Probe found codec=%s, bitrate=%s", codec, bitrate) finally: return codec, bitrate @staticmethod def _probe_codec_native(source, executable: str = 'ffmpeg') -> Tuple[Optional[str], Optional[int]]: exe = executable[:2] + 'probe' if executable in ('ffmpeg', 'avconv') else executable args = [exe, '-v', 'quiet', '-print_format', 'json', '-show_streams', '-select_streams', 'a:0', source] output = subprocess.check_output(args, timeout=20) codec = bitrate = None if output: data = json.loads(output) streamdata = data['streams'][0] codec = streamdata.get('codec_name') bitrate = int(streamdata.get('bit_rate', 0)) bitrate = max(round(bitrate/1000), 512) return codec, bitrate @staticmethod def _probe_codec_fallback(source, executable: str = 'ffmpeg') -> Tuple[Optional[str], Optional[int]]: args = [executable, '-hide_banner', '-i', source] proc = subprocess.Popen(args, creationflags=CREATE_NO_WINDOW, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = proc.communicate(timeout=20) output = out.decode('utf8') codec = bitrate = None codec_match = re.search(r"Stream #0.*?Audio: (\w+)", output) if codec_match: codec = codec_match.group(1) br_match = re.search(r"(\d+) [kK]b/s", output) if br_match: bitrate = max(int(br_match.group(1)), 512) return codec, bitrate def read(self) -> bytes: return next(self._packet_iter, b'') def is_opus(self) -> bool: return True class PCMVolumeTransformer(AudioSource, Generic[AT]): """Transforms a previous :class:`AudioSource` to have volume controls. This does not work on audio sources that have :meth:`AudioSource.is_opus` set to ``True``. Parameters ------------ original: :class:`AudioSource` The original AudioSource to transform. volume: :class:`float` The initial volume to set it to. See :attr:`volume` for more info. Raises ------- TypeError Not an audio source. ClientException The audio source is opus encoded. """ def __init__(self, original: AT, volume: float = 1.0): if not isinstance(original, AudioSource): raise TypeError(f'expected AudioSource not {original.__class__.__name__}.') if original.is_opus(): raise ClientException('AudioSource must not be Opus encoded.') self.original: AT = original self.volume = volume @property def volume(self) -> float: """Retrieves or sets the volume as a floating point percentage (e.g. ``1.0`` for 100%).""" return self._volume @volume.setter def volume(self, value: float) -> None: self._volume = max(value, 0.0) def cleanup(self) -> None: self.original.cleanup() def read(self) -> bytes: ret = self.original.read() return audioop.mul(ret, 2, min(self._volume, 2.0)) class AudioPlayer(threading.Thread): DELAY: float = OpusEncoder.FRAME_LENGTH / 1000.0 def __init__(self, source: AudioSource, client: VoiceClient, *, after=None): threading.Thread.__init__(self) self.daemon: bool = True self.source: AudioSource = source self.client: VoiceClient = client self.after: Optional[Callable[[Optional[Exception]], Any]] = after self._end: threading.Event = threading.Event() self._resumed: threading.Event = threading.Event() self._resumed.set() # we are not paused self._current_error: Optional[Exception] = None self._connected: threading.Event = client._connected self._lock: threading.Lock = threading.Lock() if after is not None and not callable(after): raise TypeError('Expected a callable for the "after" parameter.') def _do_run(self) -> None: self.loops = 0 self._start = time.perf_counter() # getattr lookup speed ups play_audio = self.client.send_audio_packet self._speak(True) while not self._end.is_set(): # are we paused? if not self._resumed.is_set(): # wait until we aren't self._resumed.wait() continue # are we disconnected from voice? if not self._connected.is_set(): # wait until we are connected self._connected.wait() # reset our internal data self.loops = 0 self._start = time.perf_counter() self.loops += 1 data = self.source.read() if not data: self.stop() break play_audio(data, encode=not self.source.is_opus()) next_time = self._start + self.DELAY * self.loops delay = max(0, self.DELAY + (next_time - time.perf_counter())) time.sleep(delay) def run(self) -> None: try: self._do_run() except Exception as exc: self._current_error = exc self.stop() finally: self.source.cleanup() self._call_after() def _call_after(self) -> None: error = self._current_error if self.after is not None: try: self.after(error) except Exception as exc: _log.exception('Calling the after function failed.') exc.__context__ = error traceback.print_exception(type(exc), exc, exc.__traceback__) elif error: msg = f'Exception in voice thread {self.name}' _log.exception(msg, exc_info=error) print(msg, file=sys.stderr) traceback.print_exception(type(error), error, error.__traceback__) def stop(self) -> None: self._end.set() self._resumed.set() self._speak(False) def pause(self, *, update_speaking: bool = True) -> None: self._resumed.clear() if update_speaking: self._speak(False) def resume(self, *, update_speaking: bool = True) -> None: self.loops = 0 self._start = time.perf_counter() self._resumed.set() if update_speaking: self._speak(True) def is_playing(self) -> bool: return self._resumed.is_set() and not self._end.is_set() def is_paused(self) -> bool: return not self._end.is_set() and not self._resumed.is_set() def _set_source(self, source: AudioSource) -> None: with self._lock: self.pause(update_speaking=False) self.source = source self.resume(update_speaking=False) def _speak(self, speaking: bool) -> None: try: asyncio.run_coroutine_threadsafe(self.client.ws.speak(speaking), self.client.loop) except Exception as e: _log.info("Speaking call in player failed: %s", e)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/player.py
player.py
from __future__ import annotations import asyncio import socket import logging import struct import threading from typing import Any, Callable, List, Optional, TYPE_CHECKING, Tuple from . import opus, utils from .backoff import ExponentialBackoff from .gateway import * from .errors import ClientException, ConnectionClosed from .player import AudioPlayer, AudioSource from .utils import MISSING if TYPE_CHECKING: from .client import Client from .guild import Guild from .state import ConnectionState from .user import ClientUser from .opus import Encoder from . import abc from .types.voice import ( GuildVoiceState as GuildVoiceStatePayload, VoiceServerUpdate as VoiceServerUpdatePayload, SupportedModes, ) has_nacl: bool try: import nacl.secret # type: ignore has_nacl = True except ImportError: has_nacl = False __all__ = ( 'VoiceProtocol', 'VoiceClient', ) _log = logging.getLogger(__name__) class VoiceProtocol: """A class that represents the Discord voice protocol. This is an abstract class. The library provides a concrete implementation under :class:`VoiceClient`. This class allows you to implement a protocol to allow for an external method of sending voice, such as Lavalink_ or a native library implementation. These classes are passed to :meth:`abc.Connectable.connect <VoiceChannel.connect>`. .. _Lavalink: https://github.com/freyacodes/Lavalink Parameters ------------ client: :class:`Client` The client (or its subclasses) that started the connection request. channel: :class:`abc.Connectable` The voice channel that is being connected to. """ def __init__(self, client: Client, channel: abc.Connectable) -> None: self.client: Client = client self.channel: abc.Connectable = channel async def on_voice_state_update(self, data: GuildVoiceStatePayload) -> None: """|coro| An abstract method that is called when the client's voice state has changed. This corresponds to ``VOICE_STATE_UPDATE``. Parameters ------------ data: :class:`dict` The raw `voice state payload`__. .. _voice_state_update_payload: https://discord.com/developers/docs/resources/voice#voice-state-object __ voice_state_update_payload_ """ raise NotImplementedError async def on_voice_server_update(self, data: VoiceServerUpdatePayload) -> None: """|coro| An abstract method that is called when initially connecting to voice. This corresponds to ``VOICE_SERVER_UPDATE``. Parameters ------------ data: :class:`dict` The raw `voice server update payload`__. .. _voice_server_update_payload: https://discord.com/developers/docs/topics/gateway#voice-server-update-voice-server-update-event-fields __ voice_server_update_payload_ """ raise NotImplementedError async def connect(self, *, timeout: float, reconnect: bool) -> None: """|coro| An abstract method called when the client initiates the connection request. When a connection is requested initially, the library calls the constructor under ``__init__`` and then calls :meth:`connect`. If :meth:`connect` fails at some point then :meth:`disconnect` is called. Within this method, to start the voice connection flow it is recommended to use :meth:`Guild.change_voice_state` to start the flow. After which, :meth:`on_voice_server_update` and :meth:`on_voice_state_update` will be called. The order that these two are called is unspecified. Parameters ------------ timeout: :class:`float` The timeout for the connection. reconnect: :class:`bool` Whether reconnection is expected. """ raise NotImplementedError async def disconnect(self, *, force: bool) -> None: """|coro| An abstract method called when the client terminates the connection. See :meth:`cleanup`. Parameters ------------ force: :class:`bool` Whether the disconnection was forced. """ raise NotImplementedError def cleanup(self) -> None: """This method *must* be called to ensure proper clean-up during a disconnect. It is advisable to call this from within :meth:`disconnect` when you are completely done with the voice protocol instance. This method removes it from the internal state cache that keeps track of currently alive voice clients. Failure to clean-up will cause subsequent connections to report that it's still connected. """ key_id, _ = self.channel._get_voice_client_key() self.client._connection._remove_voice_client(key_id) class VoiceClient(VoiceProtocol): """Represents a Discord voice connection. You do not create these, you typically get them from e.g. :meth:`VoiceChannel.connect`. Warning -------- In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through :func:`opus.load_opus`. Otherwise, your AudioSources must be opus encoded (e.g. using :class:`FFmpegOpusAudio`) or the library will not be able to transmit audio. Attributes ----------- session_id: :class:`str` The voice connection session ID. token: :class:`str` The voice connection token. endpoint: :class:`str` The endpoint we are connecting to. channel: :class:`abc.Connectable` The voice channel connected to. loop: :class:`asyncio.AbstractEventLoop` The event loop that the voice client is running on. """ endpoint_ip: str voice_port: int secret_key: List[int] ssrc: int def __init__(self, client: Client, channel: abc.Connectable): if not has_nacl: raise RuntimeError("PyNaCl library needed in order to use voice") super().__init__(client, channel) state = client._connection self.token: str = MISSING self.socket = MISSING self.loop: asyncio.AbstractEventLoop = state.loop self._state: ConnectionState = state # this will be used in the AudioPlayer thread self._connected: threading.Event = threading.Event() self._handshaking: bool = False self._potentially_reconnecting: bool = False self._voice_state_complete: asyncio.Event = asyncio.Event() self._voice_server_complete: asyncio.Event = asyncio.Event() self.mode: str = MISSING self._connections: int = 0 self.sequence: int = 0 self.timestamp: int = 0 self.timeout: float = 0 self._runner: asyncio.Task = MISSING self._player: Optional[AudioPlayer] = None self.encoder: Encoder = MISSING self._lite_nonce: int = 0 self.ws: DiscordVoiceWebSocket = MISSING warn_nacl = not has_nacl supported_modes: Tuple[SupportedModes, ...] = ( 'xsalsa20_poly1305_lite', 'xsalsa20_poly1305_suffix', 'xsalsa20_poly1305', ) @property def guild(self) -> Optional[Guild]: """Optional[:class:`Guild`]: The guild we're connected to, if applicable.""" return getattr(self.channel, 'guild', None) @property def user(self) -> ClientUser: """:class:`ClientUser`: The user connected to voice (i.e. ourselves).""" return self._state.user def checked_add(self, attr, value, limit): val = getattr(self, attr) if val + value > limit: setattr(self, attr, 0) else: setattr(self, attr, val + value) # connection related async def on_voice_state_update(self, data: GuildVoiceStatePayload) -> None: self.session_id = data['session_id'] channel_id = data['channel_id'] if not self._handshaking or self._potentially_reconnecting: # If we're done handshaking then we just need to update ourselves # If we're potentially reconnecting due to a 4014, then we need to differentiate # a channel move and an actual force disconnect if channel_id is None: # We're being disconnected so cleanup await self.disconnect() else: guild = self.guild self.channel = channel_id and guild and guild.get_channel(int(channel_id)) # type: ignore else: self._voice_state_complete.set() async def on_voice_server_update(self, data: VoiceServerUpdatePayload) -> None: if self._voice_server_complete.is_set(): _log.info('Ignoring extraneous voice server update.') return self.token = data.get('token') self.server_id = int(data['guild_id']) endpoint = data.get('endpoint') if endpoint is None or self.token is None: _log.warning('Awaiting endpoint... This requires waiting. ' \ 'If timeout occurred considering raising the timeout and reconnecting.') return self.endpoint, _, _ = endpoint.rpartition(':') if self.endpoint.startswith('wss://'): # Just in case, strip it off since we're going to add it later self.endpoint = self.endpoint[6:] # This gets set later self.endpoint_ip = MISSING self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.socket.setblocking(False) if not self._handshaking: # If we're not handshaking then we need to terminate our previous connection in the websocket await self.ws.close(4000) return self._voice_server_complete.set() async def voice_connect(self) -> None: await self.channel.guild.change_voice_state(channel=self.channel) async def voice_disconnect(self) -> None: _log.info('The voice handshake is being terminated for Channel ID %s (Guild ID %s)', self.channel.id, self.guild.id) await self.channel.guild.change_voice_state(channel=None) def prepare_handshake(self) -> None: self._voice_state_complete.clear() self._voice_server_complete.clear() self._handshaking = True _log.info('Starting voice handshake... (connection attempt %d)', self._connections + 1) self._connections += 1 def finish_handshake(self) -> None: _log.info('Voice handshake complete. Endpoint found %s', self.endpoint) self._handshaking = False self._voice_server_complete.clear() self._voice_state_complete.clear() async def connect_websocket(self) -> DiscordVoiceWebSocket: ws = await DiscordVoiceWebSocket.from_client(self) self._connected.clear() while ws.secret_key is None: await ws.poll_event() self._connected.set() return ws async def connect(self, *, reconnect: bool, timeout: float) ->None: _log.info('Connecting to voice...') self.timeout = timeout for i in range(5): self.prepare_handshake() # This has to be created before we start the flow. futures = [ self._voice_state_complete.wait(), self._voice_server_complete.wait(), ] # Start the connection flow await self.voice_connect() try: await utils.sane_wait_for(futures, timeout=timeout) except asyncio.TimeoutError: await self.disconnect(force=True) raise self.finish_handshake() try: self.ws = await self.connect_websocket() break except (ConnectionClosed, asyncio.TimeoutError): if reconnect: _log.exception('Failed to connect to voice... Retrying...') await asyncio.sleep(1 + i * 2.0) await self.voice_disconnect() continue else: raise if self._runner is MISSING: self._runner = self.loop.create_task(self.poll_voice_ws(reconnect)) async def potential_reconnect(self) -> bool: # Attempt to stop the player thread from playing early self._connected.clear() self.prepare_handshake() self._potentially_reconnecting = True try: # We only care about VOICE_SERVER_UPDATE since VOICE_STATE_UPDATE can come before we get disconnected await asyncio.wait_for(self._voice_server_complete.wait(), timeout=self.timeout) except asyncio.TimeoutError: self._potentially_reconnecting = False await self.disconnect(force=True) return False self.finish_handshake() self._potentially_reconnecting = False try: self.ws = await self.connect_websocket() except (ConnectionClosed, asyncio.TimeoutError): return False else: return True @property def latency(self) -> float: """:class:`float`: Latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This could be referred to as the Discord Voice WebSocket latency and is an analogue of user's voice latencies as seen in the Discord client. .. versionadded:: 1.4 """ ws = self.ws return float("inf") if not ws else ws.latency @property def average_latency(self) -> float: """:class:`float`: Average of most recent 20 HEARTBEAT latencies in seconds. .. versionadded:: 1.4 """ ws = self.ws return float("inf") if not ws else ws.average_latency async def poll_voice_ws(self, reconnect: bool) -> None: backoff = ExponentialBackoff() while True: try: await self.ws.poll_event() except (ConnectionClosed, asyncio.TimeoutError) as exc: if isinstance(exc, ConnectionClosed): # The following close codes are undocumented so I will document them here. # 1000 - normal closure (obviously) # 4014 - voice channel has been deleted. # 4015 - voice server has crashed if exc.code in (1000, 4015): _log.info('Disconnecting from voice normally, close code %d.', exc.code) await self.disconnect() break if exc.code == 4014: _log.info('Disconnected from voice by force... potentially reconnecting.') successful = await self.potential_reconnect() if not successful: _log.info('Reconnect was unsuccessful, disconnecting from voice normally...') await self.disconnect() break else: continue if not reconnect: await self.disconnect() raise retry = backoff.delay() _log.exception('Disconnected from voice... Reconnecting in %.2fs.', retry) self._connected.clear() await asyncio.sleep(retry) await self.voice_disconnect() try: await self.connect(reconnect=True, timeout=self.timeout) except asyncio.TimeoutError: # at this point we've retried 5 times... let's continue the loop. _log.warning('Could not connect to voice... Retrying...') continue async def disconnect(self, *, force: bool = False) -> None: """|coro| Disconnects this voice client from voice. """ if not force and not self.is_connected(): return self.stop() self._connected.clear() try: if self.ws: await self.ws.close() await self.voice_disconnect() finally: self.cleanup() if self.socket: self.socket.close() async def move_to(self, channel: abc.Snowflake) -> None: """|coro| Moves you to a different voice channel. Parameters ----------- channel: :class:`abc.Snowflake` The channel to move to. Must be a voice channel. """ await self.channel.guild.change_voice_state(channel=channel) def is_connected(self) -> bool: """Indicates if the voice client is connected to voice.""" return self._connected.is_set() # audio related def _get_voice_packet(self, data): header = bytearray(12) # Formulate rtp header header[0] = 0x80 header[1] = 0x78 struct.pack_into('>H', header, 2, self.sequence) struct.pack_into('>I', header, 4, self.timestamp) struct.pack_into('>I', header, 8, self.ssrc) encrypt_packet = getattr(self, '_encrypt_' + self.mode) return encrypt_packet(header, data) def _encrypt_xsalsa20_poly1305(self, header: bytes, data) -> bytes: box = nacl.secret.SecretBox(bytes(self.secret_key)) nonce = bytearray(24) nonce[:12] = header return header + box.encrypt(bytes(data), bytes(nonce)).ciphertext def _encrypt_xsalsa20_poly1305_suffix(self, header: bytes, data) -> bytes: box = nacl.secret.SecretBox(bytes(self.secret_key)) nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE) return header + box.encrypt(bytes(data), nonce).ciphertext + nonce def _encrypt_xsalsa20_poly1305_lite(self, header: bytes, data) -> bytes: box = nacl.secret.SecretBox(bytes(self.secret_key)) nonce = bytearray(24) nonce[:4] = struct.pack('>I', self._lite_nonce) self.checked_add('_lite_nonce', 1, 4294967295) return header + box.encrypt(bytes(data), bytes(nonce)).ciphertext + nonce[:4] def play(self, source: AudioSource, *, after: Callable[[Optional[Exception]], Any]=None) -> None: """Plays an :class:`AudioSource`. The finalizer, ``after`` is called after the source has been exhausted or an error occurred. If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be displayed as if it were raised. Parameters ----------- source: :class:`AudioSource` The audio source we're reading from. after: Callable[[Optional[:class:`Exception`]], Any] The finalizer that is called after the stream is exhausted. This function must have a single parameter, ``error``, that denotes an optional exception that was raised during playing. Raises ------- ClientException Already playing audio or not connected. TypeError Source is not a :class:`AudioSource` or after is not a callable. OpusNotLoaded Source is not opus encoded and opus is not loaded. """ if not self.is_connected(): raise ClientException('Not connected to voice.') if self.is_playing(): raise ClientException('Already playing audio.') if not isinstance(source, AudioSource): raise TypeError(f'source must be an AudioSource not {source.__class__.__name__}') if not self.encoder and not source.is_opus(): self.encoder = opus.Encoder() self._player = AudioPlayer(source, self, after=after) self._player.start() def is_playing(self) -> bool: """Indicates if we're currently playing audio.""" return self._player is not None and self._player.is_playing() def is_paused(self) -> bool: """Indicates if we're playing audio, but if we're paused.""" return self._player is not None and self._player.is_paused() def stop(self) -> None: """Stops playing audio.""" if self._player: self._player.stop() self._player = None def pause(self) -> None: """Pauses the audio playing.""" if self._player: self._player.pause() def resume(self) -> None: """Resumes the audio playing.""" if self._player: self._player.resume() @property def source(self) -> Optional[AudioSource]: """Optional[:class:`AudioSource`]: The audio source being played, if playing. This property can also be used to change the audio source currently being played. """ return self._player.source if self._player else None @source.setter def source(self, value: AudioSource) -> None: if not isinstance(value, AudioSource): raise TypeError(f'expected AudioSource not {value.__class__.__name__}.') if self._player is None: raise ValueError('Not playing anything.') self._player._set_source(value) def send_audio_packet(self, data: bytes, *, encode: bool = True) -> None: """Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: :class:`bytes` The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: :class:`bool` Indicates if ``data`` should be encoded into Opus. Raises ------- ClientException You are not connected. opus.OpusError Encoding the data failed. """ self.checked_add('sequence', 1, 65535) if encode: encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME) else: encoded_data = data packet = self._get_voice_packet(encoded_data) try: self.socket.sendto(packet, (self.endpoint_ip, self.voice_port)) except BlockingIOError: _log.warning('A packet has been dropped (seq: %s, timestamp: %s)', self.sequence, self.timestamp) self.checked_add('timestamp', opus.Encoder.SAMPLES_PER_FRAME, 4294967295)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/voice_client.py
voice_client.py
from __future__ import annotations from typing import Any, Iterator, List, Optional, TYPE_CHECKING, Tuple from .asset import Asset, AssetMixin from .utils import SnowflakeList, snowflake_time, MISSING from .partial_emoji import _EmojiTag, PartialEmoji from .user import User __all__ = ( 'Emoji', ) if TYPE_CHECKING: from .types.emoji import Emoji as EmojiPayload from .guild import Guild from .state import ConnectionState from .abc import Snowflake from .role import Role from datetime import datetime class Emoji(_EmojiTag, AssetMixin): """Represents a custom emoji. Depending on the way this object was created, some of the attributes can have a value of ``None``. .. container:: operations .. describe:: x == y Checks if two emoji are the same. .. describe:: x != y Checks if two emoji are not the same. .. describe:: hash(x) Return the emoji's hash. .. describe:: iter(x) Returns an iterator of ``(field, value)`` pairs. This allows this class to be used as an iterable in list/dict/etc constructions. .. describe:: str(x) Returns the emoji rendered for discord. Attributes ----------- name: :class:`str` The name of the emoji. id: :class:`int` The emoji's ID. require_colons: :class:`bool` If colons are required to use this emoji in the client (:PJSalt: vs PJSalt). animated: :class:`bool` Whether an emoji is animated or not. managed: :class:`bool` If this emoji is managed by a Twitch integration. guild_id: :class:`int` The guild ID the emoji belongs to. available: :class:`bool` Whether the emoji is available for use. user: Optional[:class:`User`] The user that created the emoji. This can only be retrieved using :meth:`Guild.fetch_emoji` and having the :attr:`~Permissions.manage_emojis` permission. """ __slots__: Tuple[str, ...] = ( 'require_colons', 'animated', 'managed', 'id', 'name', '_roles', 'guild_id', '_state', 'user', 'available', ) def __init__(self, *, guild: Guild, state: ConnectionState, data: EmojiPayload): self.guild_id: int = guild.id self._state: ConnectionState = state self._from_data(data) def _from_data(self, emoji: EmojiPayload): self.require_colons: bool = emoji.get('require_colons', False) self.managed: bool = emoji.get('managed', False) self.id: int = int(emoji['id']) # type: ignore self.name: str = emoji['name'] # type: ignore self.animated: bool = emoji.get('animated', False) self.available: bool = emoji.get('available', True) self._roles: SnowflakeList = SnowflakeList(map(int, emoji.get('roles', []))) user = emoji.get('user') self.user: Optional[User] = User(state=self._state, data=user) if user else None def _to_partial(self) -> PartialEmoji: return PartialEmoji(name=self.name, animated=self.animated, id=self.id) def __iter__(self) -> Iterator[Tuple[str, Any]]: for attr in self.__slots__: if attr[0] != '_': value = getattr(self, attr, None) if value is not None: yield (attr, value) def __str__(self) -> str: if self.animated: return f'<a:{self.name}:{self.id}>' return f'<:{self.name}:{self.id}>' def __repr__(self) -> str: return f'<Emoji id={self.id} name={self.name!r} animated={self.animated} managed={self.managed}>' def __eq__(self, other: Any) -> bool: return isinstance(other, _EmojiTag) and self.id == other.id def __ne__(self, other: Any) -> bool: return not self.__eq__(other) def __hash__(self) -> int: return self.id >> 22 @property def created_at(self) -> datetime: """:class:`datetime.datetime`: Returns the emoji's creation time in UTC.""" return snowflake_time(self.id) @property def url(self) -> str: """:class:`str`: Returns the URL of the emoji.""" fmt = 'gif' if self.animated else 'png' return f'{Asset.BASE}/emojis/{self.id}.{fmt}' @property def roles(self) -> List[Role]: """List[:class:`Role`]: A :class:`list` of roles that is allowed to use this emoji. If roles is empty, the emoji is unrestricted. """ guild = self.guild if guild is None: return [] return [role for role in guild.roles if self._roles.has(role.id)] @property def guild(self) -> Guild: """:class:`Guild`: The guild this emoji belongs to.""" return self._state._get_guild(self.guild_id) def is_usable(self) -> bool: """:class:`bool`: Whether the bot can use this emoji. .. versionadded:: 1.3 """ if not self.available: return False if not self._roles: return True emoji_roles, my_roles = self._roles, self.guild.me._roles return any(my_roles.has(role_id) for role_id in emoji_roles) async def delete(self, *, reason: Optional[str] = None) -> None: """|coro| Deletes the custom emoji. You must have :attr:`~Permissions.manage_emojis` permission to do this. Parameters ----------- 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.guild.id, self.id, reason=reason) async def edit(self, *, name: str = MISSING, roles: List[Snowflake] = MISSING, reason: Optional[str] = None) -> Emoji: r"""|coro| Edits the custom emoji. You must have :attr:`~Permissions.manage_emojis` permission to do this. .. versionchanged:: 2.0 The newly updated emoji is returned. Parameters ----------- name: :class:`str` The new emoji name. roles: Optional[List[:class:`~discord.abc.Snowflake`]] A list of roles that can use this emoji. An empty list can be passed to make it available to everyone. reason: Optional[:class:`str`] The reason for editing this emoji. Shows up on the audit log. Raises ------- Forbidden You are not allowed to edit emojis. HTTPException An error occurred editing the emoji. Returns -------- :class:`Emoji` The newly updated emoji. """ payload = {} if name is not MISSING: payload['name'] = name if roles is not MISSING: payload['roles'] = [role.id for role in roles] data = await self._state.http.edit_custom_emoji(self.guild.id, self.id, payload=payload, reason=reason) return Emoji(guild=self.guild, data=data, state=self._state)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/emoji.py
emoji.py
from __future__ import annotations import copy import asyncio from typing import ( Any, Callable, Dict, List, Optional, TYPE_CHECKING, Protocol, Sequence, Tuple, TypeVar, Union, overload, runtime_checkable, ) from .iterators import HistoryIterator from .context_managers import Typing from .enums import ChannelType from .errors import InvalidArgument, ClientException from .mentions import AllowedMentions from .permissions import PermissionOverwrite, Permissions from .role import Role from .invite import Invite from .file import File from .voice_client import VoiceClient, VoiceProtocol from .sticker import GuildSticker, StickerItem from . import utils __all__ = ( 'Snowflake', 'User', 'PrivateChannel', 'GuildChannel', 'Messageable', 'Connectable', ) T = TypeVar('T', bound=VoiceProtocol) if TYPE_CHECKING: from datetime import datetime from .client import Client from .user import ClientUser from .asset import Asset from .state import ConnectionState from .guild import Guild from .member import Member from .channel import CategoryChannel from .embeds import Embed from .message import Message, MessageReference, PartialMessage from .channel import TextChannel, DMChannel, GroupChannel, PartialMessageable from .threads import Thread from .enums import InviteTarget from .ui.view import View from .types.channel import ( PermissionOverwrite as PermissionOverwritePayload, Channel as ChannelPayload, GuildChannel as GuildChannelPayload, OverwriteType, ) PartialMessageableChannel = Union[TextChannel, Thread, DMChannel, PartialMessageable] MessageableChannel = Union[PartialMessageableChannel, GroupChannel] SnowflakeTime = Union["Snowflake", datetime] MISSING = utils.MISSING class _Undefined: def __repr__(self) -> str: return 'see-below' _undefined: Any = _Undefined() @runtime_checkable class Snowflake(Protocol): """An ABC that details the common operations on a Discord model. Almost all :ref:`Discord models <discord_api_models>` meet this abstract base class. If you want to create a snowflake on your own, consider using :class:`.Object`. Attributes ----------- id: :class:`int` The model's unique ID. """ __slots__ = () id: int @runtime_checkable class User(Snowflake, Protocol): """An ABC that details the common operations on a Discord user. The following implement this ABC: - :class:`~discord.User` - :class:`~discord.ClientUser` - :class:`~discord.Member` This ABC must also implement :class:`~discord.abc.Snowflake`. Attributes ----------- name: :class:`str` The user's username. discriminator: :class:`str` The user's discriminator. avatar: :class:`~discord.Asset` The avatar asset the user has. bot: :class:`bool` If the user is a bot account. """ __slots__ = () name: str discriminator: str avatar: Asset bot: bool @property def display_name(self) -> str: """:class:`str`: Returns the user's display name.""" raise NotImplementedError @property def mention(self) -> str: """:class:`str`: Returns a string that allows you to mention the given user.""" raise NotImplementedError @runtime_checkable class PrivateChannel(Snowflake, Protocol): """An ABC that details the common operations on a private Discord channel. The following implement this ABC: - :class:`~discord.DMChannel` - :class:`~discord.GroupChannel` This ABC must also implement :class:`~discord.abc.Snowflake`. Attributes ----------- me: :class:`~discord.ClientUser` The user presenting yourself. """ __slots__ = () me: ClientUser class _Overwrites: __slots__ = ('id', 'allow', 'deny', 'type') ROLE = 0 MEMBER = 1 def __init__(self, data: PermissionOverwritePayload): self.id: int = int(data['id']) self.allow: int = int(data.get('allow', 0)) self.deny: int = int(data.get('deny', 0)) self.type: OverwriteType = data['type'] def _asdict(self) -> PermissionOverwritePayload: return { 'id': self.id, 'allow': str(self.allow), 'deny': str(self.deny), 'type': self.type, } def is_role(self) -> bool: return self.type == 0 def is_member(self) -> bool: return self.type == 1 GCH = TypeVar('GCH', bound='GuildChannel') class GuildChannel: """An ABC that details the common operations on a Discord guild channel. The following implement this ABC: - :class:`~discord.TextChannel` - :class:`~discord.VoiceChannel` - :class:`~discord.CategoryChannel` - :class:`~discord.StageChannel` This ABC must also implement :class:`~discord.abc.Snowflake`. Attributes ----------- name: :class:`str` The channel name. guild: :class:`~discord.Guild` The guild the channel belongs to. 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. """ __slots__ = () id: int name: str guild: Guild type: ChannelType position: int category_id: Optional[int] _state: ConnectionState _overwrites: List[_Overwrites] if TYPE_CHECKING: def __init__(self, *, state: ConnectionState, guild: Guild, data: Dict[str, Any]): ... def __str__(self) -> str: return self.name @property def _sorting_bucket(self) -> int: raise NotImplementedError def _update(self, guild: Guild, data: Dict[str, Any]) -> None: raise NotImplementedError async def _move( self, position: int, parent_id: Optional[Any] = None, lock_permissions: bool = False, *, reason: Optional[str], ) -> None: if position < 0: raise InvalidArgument('Channel position cannot be less than 0.') http = self._state.http bucket = self._sorting_bucket channels: List[GuildChannel] = [c for c in self.guild.channels if c._sorting_bucket == bucket] channels.sort(key=lambda c: c.position) try: # remove ourselves from the channel list channels.remove(self) except ValueError: # not there somehow lol return else: index = next((i for i, c in enumerate(channels) if c.position >= position), len(channels)) # add ourselves at our designated position channels.insert(index, self) payload = [] for index, c in enumerate(channels): d: Dict[str, Any] = {'id': c.id, 'position': index} if parent_id is not _undefined and c.id == self.id: d.update(parent_id=parent_id, lock_permissions=lock_permissions) payload.append(d) await http.bulk_channel_update(self.guild.id, payload, reason=reason) async def _edit(self, options: Dict[str, Any], reason: Optional[str]) -> Optional[ChannelPayload]: try: parent = options.pop('category') except KeyError: parent_id = _undefined else: parent_id = parent and parent.id try: options['rate_limit_per_user'] = options.pop('slowmode_delay') except KeyError: pass try: rtc_region = options.pop('rtc_region') except KeyError: pass else: options['rtc_region'] = None if rtc_region is None else str(rtc_region) try: video_quality_mode = options.pop('video_quality_mode') except KeyError: pass else: options['video_quality_mode'] = int(video_quality_mode) lock_permissions = options.pop('sync_permissions', False) try: position = options.pop('position') except KeyError: if parent_id is not _undefined: if lock_permissions: category = self.guild.get_channel(parent_id) if category: options['permission_overwrites'] = [c._asdict() for c in category._overwrites] options['parent_id'] = parent_id elif lock_permissions and self.category_id is not None: # if we're syncing permissions on a pre-existing channel category without changing it # we need to update the permissions to point to the pre-existing category category = self.guild.get_channel(self.category_id) if category: options['permission_overwrites'] = [c._asdict() for c in category._overwrites] else: await self._move(position, parent_id=parent_id, lock_permissions=lock_permissions, reason=reason) overwrites = options.get('overwrites', None) if overwrites is not None: 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'] = _Overwrites.ROLE else: payload['type'] = _Overwrites.MEMBER perms.append(payload) options['permission_overwrites'] = perms try: ch_type = options['type'] except KeyError: pass else: if not isinstance(ch_type, ChannelType): raise InvalidArgument('type field must be of type ChannelType') options['type'] = ch_type.value if options: return await self._state.http.edit_channel(self.id, reason=reason, **options) def _fill_overwrites(self, data: GuildChannelPayload) -> None: self._overwrites = [] everyone_index = 0 everyone_id = self.guild.id for index, overridden in enumerate(data.get('permission_overwrites', [])): overwrite = _Overwrites(overridden) self._overwrites.append(overwrite) if overwrite.type == _Overwrites.MEMBER: continue if overwrite.id == everyone_id: # the @everyone role is not guaranteed to be the first one # in the list of permission overwrites, however the permission # resolution code kind of requires that it is the first one in # the list since it is special. So we need the index so we can # swap it to be the first one. everyone_index = index # do the swap tmp = self._overwrites if tmp: tmp[everyone_index], tmp[0] = tmp[0], tmp[everyone_index] @property def changed_roles(self) -> List[Role]: """List[:class:`~discord.Role`]: Returns a list of roles that have been overridden from their default values in the :attr:`~discord.Guild.roles` attribute.""" ret = [] g = self.guild for overwrite in filter(lambda o: o.is_role(), self._overwrites): role = g.get_role(overwrite.id) if role is None: continue role = copy.copy(role) role.permissions.handle_overwrite(overwrite.allow, overwrite.deny) ret.append(role) return ret @property def mention(self) -> str: """:class:`str`: The string that allows you to mention the channel.""" return f'<#{self.id}>' @property def created_at(self) -> datetime: """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" return utils.snowflake_time(self.id) def overwrites_for(self, obj: Union[Role, User]) -> PermissionOverwrite: """Returns the channel-specific overwrites for a member or a role. Parameters ----------- obj: Union[:class:`~discord.Role`, :class:`~discord.abc.User`] The role or user denoting whose overwrite to get. Returns --------- :class:`~discord.PermissionOverwrite` The permission overwrites for this object. """ if isinstance(obj, User): predicate = lambda p: p.is_member() elif isinstance(obj, Role): predicate = lambda p: p.is_role() else: predicate = lambda p: True for overwrite in filter(predicate, self._overwrites): if overwrite.id == obj.id: allow = Permissions(overwrite.allow) deny = Permissions(overwrite.deny) return PermissionOverwrite.from_pair(allow, deny) return PermissionOverwrite() @property def overwrites(self) -> Dict[Union[Role, Member], PermissionOverwrite]: """Returns all of the channel's overwrites. This is returned as a dictionary where the key contains the target which can be either a :class:`~discord.Role` or a :class:`~discord.Member` and the value is the overwrite as a :class:`~discord.PermissionOverwrite`. Returns -------- Dict[Union[:class:`~discord.Role`, :class:`~discord.Member`], :class:`~discord.PermissionOverwrite`] The channel's permission overwrites. """ ret = {} for ow in self._overwrites: allow = Permissions(ow.allow) deny = Permissions(ow.deny) overwrite = PermissionOverwrite.from_pair(allow, deny) target = None if ow.is_role(): target = self.guild.get_role(ow.id) elif ow.is_member(): target = self.guild.get_member(ow.id) # TODO: There is potential data loss here in the non-chunked # case, i.e. target is None because get_member returned nothing. # This can be fixed with a slight breaking change to the return type, # i.e. adding discord.Object to the list of it # However, for now this is an acceptable compromise. if target is not None: ret[target] = overwrite return ret @property def category(self) -> Optional[CategoryChannel]: """Optional[:class:`~discord.CategoryChannel`]: The category this channel belongs to. If there is no category then this is ``None``. """ return self.guild.get_channel(self.category_id) # type: ignore @property def permissions_synced(self) -> bool: """:class:`bool`: Whether or not the permissions for this channel are synced with the category it belongs to. If there is no category then this is ``False``. .. versionadded:: 1.3 """ if self.category_id is None: return False category = self.guild.get_channel(self.category_id) return bool(category and category.overwrites == self.overwrites) def permissions_for(self, obj: Union[Member, Role], /) -> Permissions: """Handles permission resolution for the :class:`~discord.Member` or :class:`~discord.Role`. This function takes into consideration the following cases: - Guild owner - Guild roles - Channel overrides - Member overrides If a :class:`~discord.Role` is passed, then it checks the permissions someone with that role would have, which is essentially: - The default role permissions - The permissions of the role used as a parameter - The default role permission overwrites - The permission overwrites of the role used as a parameter .. versionchanged:: 2.0 The object passed in can now be a role object. Parameters ---------- obj: Union[:class:`~discord.Member`, :class:`~discord.Role`] The object to resolve permissions for. This could be either a member or a role. If it's a role then member overwrites are not computed. Returns ------- :class:`~discord.Permissions` The resolved permissions for the member or role. """ # The current cases can be explained as: # Guild owner get all permissions -- no questions asked. Otherwise... # The @everyone role gets the first application. # After that, the applied roles that the user has in the channel # (or otherwise) are then OR'd together. # After the role permissions are resolved, the member permissions # have to take into effect. # After all that is done.. you have to do the following: # If manage permissions is True, then all permissions are set to True. # The operation first takes into consideration the denied # and then the allowed. if self.guild.owner_id == obj.id: return Permissions.all() default = self.guild.default_role base = Permissions(default.permissions.value) # Handle the role case first if isinstance(obj, Role): base.value |= obj._permissions if base.administrator: return Permissions.all() # Apply @everyone allow/deny first since it's special try: maybe_everyone = self._overwrites[0] if maybe_everyone.id == self.guild.id: base.handle_overwrite(allow=maybe_everyone.allow, deny=maybe_everyone.deny) except IndexError: pass if obj.is_default(): return base overwrite = utils.get(self._overwrites, type=_Overwrites.ROLE, id=obj.id) if overwrite is not None: base.handle_overwrite(overwrite.allow, overwrite.deny) return base roles = obj._roles get_role = self.guild.get_role # Apply guild roles that the member has. for role_id in roles: role = get_role(role_id) if role is not None: base.value |= role._permissions # Guild-wide Administrator -> True for everything # Bypass all channel-specific overrides if base.administrator: return Permissions.all() # Apply @everyone allow/deny first since it's special try: maybe_everyone = self._overwrites[0] if maybe_everyone.id == self.guild.id: base.handle_overwrite(allow=maybe_everyone.allow, deny=maybe_everyone.deny) remaining_overwrites = self._overwrites[1:] else: remaining_overwrites = self._overwrites except IndexError: remaining_overwrites = self._overwrites denies = 0 allows = 0 # Apply channel specific role permission overwrites for overwrite in remaining_overwrites: if overwrite.is_role() and roles.has(overwrite.id): denies |= overwrite.deny allows |= overwrite.allow base.handle_overwrite(allow=allows, deny=denies) # Apply member specific permission overwrites for overwrite in remaining_overwrites: if overwrite.is_member() and overwrite.id == obj.id: base.handle_overwrite(allow=overwrite.allow, deny=overwrite.deny) break # if you can't send a message in a channel then you can't have certain # permissions as well if not base.send_messages: base.send_tts_messages = False base.mention_everyone = False base.embed_links = False base.attach_files = False # if you can't read a channel then you have no permissions there if not base.read_messages: denied = Permissions.all_channel() base.value &= ~denied.value return base async def delete(self, *, reason: Optional[str] = None) -> None: """|coro| Deletes the channel. You must have :attr:`~discord.Permissions.manage_channels` permission to use this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this channel. Shows up on the audit log. Raises ------- ~discord.Forbidden You do not have proper permissions to delete the channel. ~discord.NotFound The channel was not found or was already deleted. ~discord.HTTPException Deleting the channel failed. """ await self._state.http.delete_channel(self.id, reason=reason) @overload async def set_permissions( self, target: Union[Member, Role], *, overwrite: Optional[Union[PermissionOverwrite, _Undefined]] = ..., reason: Optional[str] = ..., ) -> None: ... @overload async def set_permissions( self, target: Union[Member, Role], *, reason: Optional[str] = ..., **permissions: bool, ) -> None: ... async def set_permissions(self, target, *, overwrite=_undefined, reason=None, **permissions): r"""|coro| Sets the channel specific permission overwrites for a target in the channel. The ``target`` parameter should either be a :class:`~discord.Member` or a :class:`~discord.Role` that belongs to guild. The ``overwrite`` parameter, if given, must either be ``None`` or :class:`~discord.PermissionOverwrite`. For convenience, you can pass in keyword arguments denoting :class:`~discord.Permissions` attributes. If this is done, then you cannot mix the keyword arguments with the ``overwrite`` parameter. If the ``overwrite`` parameter is ``None``, then the permission overwrites are deleted. You must have the :attr:`~discord.Permissions.manage_roles` permission to use this. .. note:: This method *replaces* the old overwrites with the ones given. Examples ---------- Setting allow and deny: :: await message.channel.set_permissions(message.author, read_messages=True, send_messages=False) Deleting overwrites :: await channel.set_permissions(member, overwrite=None) Using :class:`~discord.PermissionOverwrite` :: overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite) Parameters ----------- target: Union[:class:`~discord.Member`, :class:`~discord.Role`] The member or role to overwrite permissions for. overwrite: Optional[:class:`~discord.PermissionOverwrite`] The permissions to allow and deny to the target, or ``None`` to delete the overwrite. \*\*permissions A keyword argument list of permissions to set for ease of use. Cannot be mixed with ``overwrite``. reason: Optional[:class:`str`] The reason for doing this action. Shows up on the audit log. Raises ------- ~discord.Forbidden You do not have permissions to edit channel specific permissions. ~discord.HTTPException Editing channel specific permissions failed. ~discord.NotFound The role or member being edited is not part of the guild. ~discord.InvalidArgument The overwrite parameter invalid or the target type was not :class:`~discord.Role` or :class:`~discord.Member`. """ http = self._state.http if isinstance(target, User): perm_type = _Overwrites.MEMBER elif isinstance(target, Role): perm_type = _Overwrites.ROLE else: raise InvalidArgument('target parameter must be either Member or Role') if overwrite is _undefined: if len(permissions) == 0: raise InvalidArgument('No overwrite provided.') try: overwrite = PermissionOverwrite(**permissions) except (ValueError, TypeError): raise InvalidArgument('Invalid permissions given to keyword arguments.') else: if len(permissions) > 0: raise InvalidArgument('Cannot mix overwrite and keyword arguments.') # TODO: wait for event if overwrite is None: await http.delete_channel_permissions(self.id, target.id, reason=reason) elif isinstance(overwrite, PermissionOverwrite): (allow, deny) = overwrite.pair() await http.edit_channel_permissions(self.id, target.id, allow.value, deny.value, perm_type, reason=reason) else: raise InvalidArgument('Invalid overwrite type provided.') async def _clone_impl( self: GCH, base_attrs: Dict[str, Any], *, name: Optional[str] = None, reason: Optional[str] = None, ) -> GCH: base_attrs['permission_overwrites'] = [x._asdict() for x in self._overwrites] base_attrs['parent_id'] = self.category_id base_attrs['name'] = name or self.name guild_id = self.guild.id cls = self.__class__ data = await self._state.http.create_channel(guild_id, self.type.value, reason=reason, **base_attrs) obj = cls(state=self._state, guild=self.guild, data=data) # temporarily add it to the cache self.guild._channels[obj.id] = obj # type: ignore return obj async def clone(self: GCH, *, name: Optional[str] = None, reason: Optional[str] = None) -> GCH: """|coro| Clones this channel. This creates a channel with the same properties as this channel. You must have the :attr:`~discord.Permissions.manage_channels` permission to do this. .. versionadded:: 1.1 Parameters ------------ name: Optional[:class:`str`] The name of the new channel. If not provided, defaults to this channel name. reason: Optional[:class:`str`] The reason for cloning this channel. Shows up on the audit log. Raises ------- ~discord.Forbidden You do not have the proper permissions to create this channel. ~discord.HTTPException Creating the channel failed. Returns -------- :class:`.abc.GuildChannel` The channel that was created. """ raise NotImplementedError @overload async def move( self, *, beginning: bool, offset: int = MISSING, category: Optional[Snowflake] = MISSING, sync_permissions: bool = MISSING, reason: Optional[str] = MISSING, ) -> None: ... @overload async def move( self, *, end: bool, offset: int = MISSING, category: Optional[Snowflake] = MISSING, sync_permissions: bool = MISSING, reason: str = MISSING, ) -> None: ... @overload async def move( self, *, before: Snowflake, offset: int = MISSING, category: Optional[Snowflake] = MISSING, sync_permissions: bool = MISSING, reason: str = MISSING, ) -> None: ... @overload async def move( self, *, after: Snowflake, offset: int = MISSING, category: Optional[Snowflake] = MISSING, sync_permissions: bool = MISSING, reason: str = MISSING, ) -> None: ... async def move(self, **kwargs) -> None: """|coro| A rich interface to help move a channel relative to other channels. If exact position movement is required, ``edit`` should be used instead. You must have the :attr:`~discord.Permissions.manage_channels` permission to do this. .. note:: Voice channels will always be sorted below text channels. This is a Discord limitation. .. versionadded:: 1.7 Parameters ------------ beginning: :class:`bool` Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with ``end``, ``before``, and ``after``. end: :class:`bool` Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with ``beginning``, ``before``, and ``after``. before: :class:`~discord.abc.Snowflake` The channel that should be before our current channel. This is mutually exclusive with ``beginning``, ``end``, and ``after``. after: :class:`~discord.abc.Snowflake` The channel that should be after our current channel. This is mutually exclusive with ``beginning``, ``end``, and ``before``. offset: :class:`int` The number of channels to offset the move by. For example, an offset of ``2`` with ``beginning=True`` would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the ``beginning``, ``end``, ``before``, and ``after`` parameters. category: Optional[:class:`~discord.abc.Snowflake`] The category to move this channel under. If ``None`` is given then it moves it out of the category. This parameter is ignored if moving a category channel. sync_permissions: :class:`bool` Whether to sync the permissions with the category (if given). reason: :class:`str` The reason for the move. Raises ------- InvalidArgument An invalid position was given or a bad mix of arguments were passed. Forbidden You do not have permissions to move the channel. HTTPException Moving the channel failed. """ if not kwargs: return beginning, end = kwargs.get('beginning'), kwargs.get('end') before, after = kwargs.get('before'), kwargs.get('after') offset = kwargs.get('offset', 0) if sum(bool(a) for a in (beginning, end, before, after)) > 1: raise InvalidArgument('Only one of [before, after, end, beginning] can be used.') bucket = self._sorting_bucket parent_id = kwargs.get('category', MISSING) # fmt: off channels: List[GuildChannel] if parent_id not in (MISSING, None): parent_id = parent_id.id channels = [ ch for ch in self.guild.channels if ch._sorting_bucket == bucket and ch.category_id == parent_id ] else: channels = [ ch for ch in self.guild.channels if ch._sorting_bucket == bucket and ch.category_id == self.category_id ] # fmt: on channels.sort(key=lambda c: (c.position, c.id)) try: # Try to remove ourselves from the channel list channels.remove(self) except ValueError: # If we're not there then it's probably due to not being in the category pass index = None if beginning: index = 0 elif end: index = len(channels) elif before: index = next((i for i, c in enumerate(channels) if c.id == before.id), None) elif after: index = next((i + 1 for i, c in enumerate(channels) if c.id == after.id), None) if index is None: raise InvalidArgument('Could not resolve appropriate move position') channels.insert(max((index + offset), 0), self) payload = [] lock_permissions = kwargs.get('sync_permissions', False) reason = kwargs.get('reason') for index, channel in enumerate(channels): d = {'id': channel.id, 'position': index} if parent_id is not MISSING and channel.id == self.id: d.update(parent_id=parent_id, lock_permissions=lock_permissions) payload.append(d) await self._state.http.bulk_channel_update(self.guild.id, payload, reason=reason) async def create_invite( self, *, reason: Optional[str] = None, max_age: int = 0, max_uses: int = 0, temporary: bool = False, unique: bool = True, target_type: Optional[InviteTarget] = None, target_user: Optional[User] = None, target_application_id: Optional[int] = None, ) -> Invite: """|coro| Creates an instant invite from a text or voice channel. You must have the :attr:`~discord.Permissions.create_instant_invite` permission to do this. Parameters ------------ max_age: :class:`int` How long the invite should last in seconds. If it's 0 then the invite doesn't expire. Defaults to ``0``. max_uses: :class:`int` How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to ``0``. temporary: :class:`bool` Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to ``False``. unique: :class:`bool` Indicates if a unique invite URL should be created. Defaults to True. If this is set to ``False`` then it will return a previously created invite. reason: Optional[:class:`str`] The reason for creating this invite. Shows up on the audit log. target_type: Optional[:class:`.InviteTarget`] The type of target for the voice channel invite, if any. .. versionadded:: 2.0 target_user: Optional[:class:`User`] The user whose stream to display for this invite, required if `target_type` is `TargetType.stream`. The user must be streaming in the channel. .. versionadded:: 2.0 target_application_id:: Optional[:class:`int`] The id of the embedded application for the invite, required if `target_type` is `TargetType.embedded_application`. .. versionadded:: 2.0 Raises ------- ~discord.HTTPException Invite creation failed. ~discord.NotFound The channel that was passed is a category or an invalid channel. Returns -------- :class:`~discord.Invite` The invite that was created. """ data = await self._state.http.create_invite( self.id, reason=reason, max_age=max_age, max_uses=max_uses, temporary=temporary, unique=unique, target_type=target_type.value if target_type else None, target_user_id=target_user.id if target_user else None, target_application_id=target_application_id, ) return Invite.from_incomplete(data=data, state=self._state) async def invites(self) -> List[Invite]: """|coro| Returns a list of all active instant invites from this channel. You must have :attr:`~discord.Permissions.manage_channels` to get this information. Raises ------- ~discord.Forbidden You do not have proper permissions to get the information. ~discord.HTTPException An error occurred while fetching the information. Returns ------- List[:class:`~discord.Invite`] The list of invites that are currently active. """ state = self._state data = await state.http.invites_from_channel(self.id) guild = self.guild return [Invite(state=state, data=invite, channel=self, guild=guild) for invite in data] class Messageable: """An ABC that details the common operations on a model that can send messages. The following implement this ABC: - :class:`~discord.TextChannel` - :class:`~discord.DMChannel` - :class:`~discord.GroupChannel` - :class:`~discord.User` - :class:`~discord.Member` - :class:`~discord.ext.commands.Context` - :class:`~discord.Thread` """ __slots__ = () _state: ConnectionState async def _get_channel(self) -> MessageableChannel: raise NotImplementedError @overload async def send( self, content: Optional[str] = ..., *, tts: bool = ..., embed: Embed = ..., file: File = ..., stickers: Sequence[Union[GuildSticker, StickerItem]] = ..., delete_after: float = ..., nonce: Union[str, int] = ..., allowed_mentions: AllowedMentions = ..., reference: Union[Message, MessageReference, PartialMessage] = ..., mention_author: bool = ..., view: View = ..., ) -> Message: ... @overload async def send( self, content: Optional[str] = ..., *, tts: bool = ..., embed: Embed = ..., files: List[File] = ..., stickers: Sequence[Union[GuildSticker, StickerItem]] = ..., delete_after: float = ..., nonce: Union[str, int] = ..., allowed_mentions: AllowedMentions = ..., reference: Union[Message, MessageReference, PartialMessage] = ..., mention_author: bool = ..., view: View = ..., ) -> Message: ... @overload async def send( self, content: Optional[str] = ..., *, tts: bool = ..., embeds: List[Embed] = ..., file: File = ..., stickers: Sequence[Union[GuildSticker, StickerItem]] = ..., delete_after: float = ..., nonce: Union[str, int] = ..., allowed_mentions: AllowedMentions = ..., reference: Union[Message, MessageReference, PartialMessage] = ..., mention_author: bool = ..., view: View = ..., ) -> Message: ... @overload async def send( self, content: Optional[str] = ..., *, tts: bool = ..., embeds: List[Embed] = ..., files: List[File] = ..., stickers: Sequence[Union[GuildSticker, StickerItem]] = ..., delete_after: float = ..., nonce: Union[str, int] = ..., allowed_mentions: AllowedMentions = ..., reference: Union[Message, MessageReference, PartialMessage] = ..., mention_author: bool = ..., view: View = ..., ) -> Message: ... async def send( self, content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, ): """|coro| Sends a message to the destination with the content given. The content must be a type that can convert to a string through ``str(content)``. If the content is set to ``None`` (the default), then the ``embed`` parameter must be provided. To upload a single file, the ``file`` parameter should be used with a single :class:`~discord.File` object. To upload multiple files, the ``files`` parameter should be used with a :class:`list` of :class:`~discord.File` objects. **Specifying both parameters will lead to an exception**. To upload a single embed, the ``embed`` parameter should be used with a single :class:`~discord.Embed` object. To upload multiple embeds, the ``embeds`` parameter should be used with a :class:`list` of :class:`~discord.Embed` objects. **Specifying both parameters will lead to an exception**. Parameters ------------ content: Optional[:class:`str`] The content of the message to send. tts: :class:`bool` Indicates if the message should be sent using text-to-speech. embed: :class:`~discord.Embed` The rich embed for the content. file: :class:`~discord.File` The file to upload. files: List[:class:`~discord.File`] A list of files to upload. Must be a maximum of 10. nonce: :class:`int` The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. delete_after: :class:`float` If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored. allowed_mentions: :class:`~discord.AllowedMentions` Controls the mentions being processed in this message. If this is passed, then the object is merged with :attr:`~discord.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:`~discord.Client.allowed_mentions`. If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions` are used instead. .. versionadded:: 1.4 reference: Union[:class:`~discord.Message`, :class:`~discord.MessageReference`, :class:`~discord.PartialMessage`] A reference to the :class:`~discord.Message` to which you are replying, this can be created using :meth:`~discord.Message.to_reference` or passed directly as a :class:`~discord.Message`. You can control whether this mentions the author of the referenced message using the :attr:`~discord.AllowedMentions.replied_user` attribute of ``allowed_mentions`` or by setting ``mention_author``. .. versionadded:: 1.6 mention_author: Optional[:class:`bool`] If set, overrides the :attr:`~discord.AllowedMentions.replied_user` attribute of ``allowed_mentions``. .. versionadded:: 1.6 view: :class:`discord.ui.View` A Discord UI View to add to the message. embeds: List[:class:`~discord.Embed`] A list of embeds to upload. Must be a maximum of 10. .. versionadded:: 2.0 stickers: Sequence[Union[:class:`~discord.GuildSticker`, :class:`~discord.StickerItem`]] A list of stickers to upload. Must be a maximum of 3. .. versionadded:: 2.0 Raises -------- ~discord.HTTPException Sending the message failed. ~discord.Forbidden You do not have the proper permissions to send the message. ~discord.InvalidArgument The ``files`` list is not of the appropriate size, you specified both ``file`` and ``files``, or you specified both ``embed`` and ``embeds``, or the ``reference`` object is not a :class:`~discord.Message`, :class:`~discord.MessageReference` or :class:`~discord.PartialMessage`. Returns --------- :class:`~discord.Message` The message that was sent. """ channel = await self._get_channel() state = self._state content = str(content) if content is not None else None if embed is not None and embeds is not None: raise InvalidArgument('cannot pass both embed and embeds parameter to send()') if embed is not None: embed = embed.to_dict() elif embeds is not None: if len(embeds) > 10: raise InvalidArgument('embeds parameter must be a list of up to 10 elements') embeds = [embed.to_dict() for embed in embeds] if stickers is not None: stickers = [sticker.id for sticker in stickers] if allowed_mentions is not None: if state.allowed_mentions is not None: allowed_mentions = state.allowed_mentions.merge(allowed_mentions).to_dict() else: allowed_mentions = allowed_mentions.to_dict() else: allowed_mentions = state.allowed_mentions and state.allowed_mentions.to_dict() if mention_author is not None: allowed_mentions = allowed_mentions or AllowedMentions().to_dict() allowed_mentions['replied_user'] = bool(mention_author) if reference is not None: try: reference = reference.to_message_reference_dict() except AttributeError: raise InvalidArgument('reference parameter must be Message, MessageReference, or PartialMessage') from None if view: if not hasattr(view, '__discord_ui_view__'): raise InvalidArgument(f'view parameter must be View not {view.__class__!r}') components = view.to_components() else: components = None if file is not None and files is not None: raise InvalidArgument('cannot pass both file and files parameter to send()') if file is not None: if not isinstance(file, File): raise InvalidArgument('file parameter must be File') try: data = await state.http.send_files( channel.id, files=[file], allowed_mentions=allowed_mentions, content=content, tts=tts, embed=embed, embeds=embeds, nonce=nonce, message_reference=reference, stickers=stickers, components=components, ) finally: file.close() elif files is not None: if len(files) > 10: raise InvalidArgument('files parameter must be a list of up to 10 elements') elif not all(isinstance(file, File) for file in files): raise InvalidArgument('files parameter must be a list of File') try: data = await state.http.send_files( channel.id, files=files, content=content, tts=tts, embed=embed, embeds=embeds, nonce=nonce, allowed_mentions=allowed_mentions, message_reference=reference, stickers=stickers, components=components, ) finally: for f in files: f.close() else: data = await state.http.send_message( channel.id, content, tts=tts, embed=embed, embeds=embeds, nonce=nonce, allowed_mentions=allowed_mentions, message_reference=reference, stickers=stickers, components=components, ) ret = state.create_message(channel=channel, data=data) if view: state.store_view(view, ret.id) if delete_after is not None: await ret.delete(delay=delete_after) return ret async def trigger_typing(self) -> None: """|coro| Triggers a *typing* indicator to the destination. *Typing* indicator will go away after 10 seconds, or after a message is sent. """ channel = await self._get_channel() await self._state.http.send_typing(channel.id) def typing(self) -> Typing: """Returns a context manager that allows you to type for an indefinite period of time. This is useful for denoting long computations in your bot. .. note:: This is both a regular context manager and an async context manager. This means that both ``with`` and ``async with`` work with this. Example Usage: :: async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!') """ return Typing(self) async def fetch_message(self, id: int, /) -> Message: """|coro| Retrieves a single :class:`~discord.Message` from the destination. Parameters ------------ id: :class:`int` The message ID to look for. Raises -------- ~discord.NotFound The specified message was not found. ~discord.Forbidden You do not have the permissions required to get a message. ~discord.HTTPException Retrieving the message failed. Returns -------- :class:`~discord.Message` The message asked for. """ channel = await self._get_channel() data = await self._state.http.get_message(channel.id, id) return self._state.create_message(channel=channel, data=data) async def pins(self) -> List[Message]: """|coro| Retrieves all messages that are currently pinned in the channel. .. note:: Due to a limitation with the Discord API, the :class:`.Message` objects returned by this method do not contain complete :attr:`.Message.reactions` data. Raises ------- ~discord.HTTPException Retrieving the pinned messages failed. Returns -------- List[:class:`~discord.Message`] The messages that are currently pinned. """ channel = await self._get_channel() state = self._state data = await state.http.pins_from(channel.id) return [state.create_message(channel=channel, data=m) for m in data] def history( self, *, limit: Optional[int] = 100, before: Optional[SnowflakeTime] = None, after: Optional[SnowflakeTime] = None, around: Optional[SnowflakeTime] = None, oldest_first: Optional[bool] = None, ) -> HistoryIterator: """Returns an :class:`~discord.AsyncIterator` that enables receiving the destination's message history. You must have :attr:`~discord.Permissions.read_message_history` permissions to use this. Examples --------- Usage :: counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1 Flattening into a list: :: messages = await channel.history(limit=123).flatten() # messages is now a list of Message... All parameters are optional. Parameters ----------- limit: Optional[:class:`int`] The number of messages to retrieve. If ``None``, retrieves every message in the channel. Note, however, that this would make it a slow operation. before: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]] Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. after: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]] Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. around: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]] Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages. oldest_first: Optional[:class:`bool`] If set to ``True``, return messages in oldest->newest order. Defaults to ``True`` if ``after`` is specified, otherwise ``False``. Raises ------ ~discord.Forbidden You do not have permissions to get channel message history. ~discord.HTTPException The request to get message history failed. Yields ------- :class:`~discord.Message` The message with the message data parsed. """ return HistoryIterator(self, limit=limit, before=before, after=after, around=around, oldest_first=oldest_first) class Connectable(Protocol): """An ABC that details the common operations on a channel that can connect to a voice server. The following implement this ABC: - :class:`~discord.VoiceChannel` - :class:`~discord.StageChannel` Note ---- This ABC is not decorated with :func:`typing.runtime_checkable`, so will fail :func:`isinstance`/:func:`issubclass` checks. """ __slots__ = () _state: ConnectionState def _get_voice_client_key(self) -> Tuple[int, str]: raise NotImplementedError def _get_voice_state_pair(self) -> Tuple[int, int]: raise NotImplementedError async def connect( self, *, timeout: float = 60.0, reconnect: bool = True, cls: Callable[[Client, Connectable], T] = VoiceClient, ) -> T: """|coro| Connects to voice and creates a :class:`VoiceClient` to establish your connection to the voice server. This requires :attr:`Intents.voice_states`. Parameters ----------- timeout: :class:`float` The timeout in seconds to wait for the voice endpoint. reconnect: :class:`bool` Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down. cls: Type[:class:`VoiceProtocol`] A type that subclasses :class:`~discord.VoiceProtocol` to connect with. Defaults to :class:`~discord.VoiceClient`. Raises ------- asyncio.TimeoutError Could not connect to the voice channel in time. ~discord.ClientException You are already connected to a voice channel. ~discord.opus.OpusNotLoaded The opus library has not been loaded. Returns -------- :class:`~discord.VoiceProtocol` A voice client that is fully connected to the voice server. """ key_id, _ = self._get_voice_client_key() state = self._state if state._get_voice_client(key_id): raise ClientException('Already connected to a voice channel.') client = state._get_client() voice = cls(client, self) if not isinstance(voice, VoiceProtocol): raise TypeError('Type must meet VoiceProtocol abstract base class.') state._add_voice_client(key_id, voice) try: await voice.connect(timeout=timeout, reconnect=reconnect) except asyncio.TimeoutError: try: await voice.disconnect(force=True) except Exception: # we don't care if disconnect failed because connection failed pass raise # re-raise return voice
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/abc.py
abc.py
from __future__ import annotations import asyncio import json import logging import sys from typing import ( Any, ClassVar, Coroutine, Dict, Iterable, List, Optional, Sequence, TYPE_CHECKING, Tuple, Type, TypeVar, Union, ) from urllib.parse import quote as _uriquote import weakref import aiohttp from .errors import HTTPException, Forbidden, NotFound, LoginFailure, DiscordServerError, GatewayNotFound, InvalidArgument from .gateway import DiscordClientWebSocketResponse from . import __version__, utils from .utils import MISSING _log = logging.getLogger(__name__) if TYPE_CHECKING: from .file import File from .enums import ( AuditLogAction, InteractionResponseType, ) from .types import ( appinfo, audit_log, channel, components, emoji, embed, guild, integration, interactions, invite, member, message, template, role, user, webhook, channel, widget, threads, voice, sticker, ) from .types.snowflake import Snowflake, SnowflakeList from types import TracebackType T = TypeVar('T') BE = TypeVar('BE', bound=BaseException) MU = TypeVar('MU', bound='MaybeUnlock') Response = Coroutine[Any, Any, T] 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 class Route: BASE: ClassVar[str] = 'https://discord.com/api/v8' def __init__(self, method: str, path: str, **parameters: Any) -> None: self.path: str = path self.method: str = method url = self.BASE + self.path if parameters: url = url.format_map({k: _uriquote(v) if isinstance(v, str) else v for k, v in parameters.items()}) self.url: str = url # major parameters: self.channel_id: Optional[Snowflake] = parameters.get('channel_id') self.guild_id: Optional[Snowflake] = parameters.get('guild_id') self.webhook_id: Optional[Snowflake] = parameters.get('webhook_id') self.webhook_token: Optional[str] = parameters.get('webhook_token') @property def bucket(self) -> str: # the bucket is just method + path w/ major parameters return f'{self.channel_id}:{self.guild_id}:{self.path}' class MaybeUnlock: def __init__(self, lock: asyncio.Lock) -> None: self.lock: asyncio.Lock = lock self._unlock: bool = True def __enter__(self: MU) -> MU: return self def defer(self) -> None: self._unlock = False def __exit__( self, exc_type: Optional[Type[BE]], exc: Optional[BE], traceback: Optional[TracebackType], ) -> None: if self._unlock: self.lock.release() # For some reason, the Discord voice websocket expects this header to be # completely lowercase while aiohttp respects spec and does it as case-insensitive aiohttp.hdrs.WEBSOCKET = 'websocket' # type: ignore class HTTPClient: """Represents an HTTP client sending HTTP requests to the Discord API.""" def __init__( self, connector: Optional[aiohttp.BaseConnector] = None, *, proxy: Optional[str] = None, proxy_auth: Optional[aiohttp.BasicAuth] = None, loop: Optional[asyncio.AbstractEventLoop] = None, unsync_clock: bool = True, ) -> None: self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() if loop is None else loop self.connector = connector self.__session: aiohttp.ClientSession = MISSING # filled in static_login self._locks: weakref.WeakValueDictionary = weakref.WeakValueDictionary() self._global_over: asyncio.Event = asyncio.Event() self._global_over.set() self.token: Optional[str] = None self.bot_token: bool = False self.proxy: Optional[str] = proxy self.proxy_auth: Optional[aiohttp.BasicAuth] = proxy_auth self.use_clock: bool = not unsync_clock user_agent = 'DiscordBot (https://github.com/Rapptz/discord.py {0}) Python/{1[0]}.{1[1]} aiohttp/{2}' self.user_agent: str = user_agent.format(__version__, sys.version_info, aiohttp.__version__) def recreate(self) -> None: if self.__session.closed: self.__session = aiohttp.ClientSession( connector=self.connector, ws_response_class=DiscordClientWebSocketResponse ) async def ws_connect(self, url: str, *, compress: int = 0) -> Any: kwargs = { 'proxy_auth': self.proxy_auth, 'proxy': self.proxy, 'max_msg_size': 0, 'timeout': 30.0, 'autoclose': False, 'headers': { 'User-Agent': self.user_agent, }, 'compress': compress, } return await self.__session.ws_connect(url, **kwargs) async def request( self, route: Route, *, files: Optional[Sequence[File]] = None, form: Optional[Iterable[Dict[str, Any]]] = None, **kwargs: Any, ) -> Any: bucket = route.bucket method = route.method url = route.url lock = self._locks.get(bucket) if lock is None: lock = asyncio.Lock() if bucket is not None: self._locks[bucket] = lock # header creation headers: Dict[str, str] = { 'User-Agent': self.user_agent, } if self.token is not None: headers['Authorization'] = 'Bot ' + self.token # some checking if it's a JSON request if 'json' in kwargs: headers['Content-Type'] = 'application/json' kwargs['data'] = utils._to_json(kwargs.pop('json')) try: reason = kwargs.pop('reason') except KeyError: pass else: if reason: headers['X-Audit-Log-Reason'] = _uriquote(reason, safe='/ ') kwargs['headers'] = headers # Proxy support if self.proxy is not None: kwargs['proxy'] = self.proxy if self.proxy_auth is not None: kwargs['proxy_auth'] = self.proxy_auth if not self._global_over.is_set(): # wait until the global lock is complete await self._global_over.wait() response: Optional[aiohttp.ClientResponse] = None data: Optional[Union[Dict[str, Any], str]] = None await lock.acquire() with MaybeUnlock(lock) as maybe_lock: for tries in range(5): if files: for f in files: f.reset(seek=tries) if form: form_data = aiohttp.FormData() for params in form: form_data.add_field(**params) kwargs['data'] = form_data try: async with self.__session.request(method, url, **kwargs) as response: _log.debug('%s %s with %s has returned %s', method, url, kwargs.get('data'), response.status) # even errors have text involved in them so this is safe to call data = await json_or_text(response) # check if we have rate limit header information remaining = response.headers.get('X-Ratelimit-Remaining') if remaining == '0' and response.status != 429: # we've depleted our current bucket delta = utils._parse_ratelimit_header(response, use_clock=self.use_clock) _log.debug('A rate limit bucket has been exhausted (bucket: %s, retry: %s).', bucket, delta) maybe_lock.defer() self.loop.call_later(delta, lock.release) # the request was successful so just return the text/json if 300 > response.status >= 200: _log.debug('%s %s has received %s', method, url, data) return data # we are being rate limited if response.status == 429: if not response.headers.get('Via') or isinstance(data, str): # Banned by Cloudflare more than likely. raise HTTPException(response, data) fmt = 'We are being rate limited. Retrying in %.2f seconds. Handled under the bucket "%s"' # sleep a bit retry_after: float = data['retry_after'] _log.warning(fmt, retry_after, bucket) # check if it's a global rate limit is_global = data.get('global', False) if is_global: _log.warning('Global rate limit has been hit. Retrying in %.2f seconds.', retry_after) self._global_over.clear() await asyncio.sleep(retry_after) _log.debug('Done sleeping for the rate limit. Retrying...') # release the global lock now that the # global rate limit has passed if is_global: self._global_over.set() _log.debug('Global rate limit is now over.') continue # we've received a 500, 502, or 504, unconditional retry if response.status in {500, 502, 504}: await asyncio.sleep(1 + tries * 2) continue # the usual error cases if response.status == 403: raise Forbidden(response, data) elif response.status == 404: raise NotFound(response, data) elif response.status >= 500: raise DiscordServerError(response, data) else: raise HTTPException(response, data) # This is handling exceptions from the request except OSError as e: # Connection reset by peer if tries < 4 and e.errno in (54, 10054): await asyncio.sleep(1 + tries * 2) continue raise if response is not None: # We've run out of retries, raise. if response.status >= 500: raise DiscordServerError(response, data) raise HTTPException(response, data) raise RuntimeError('Unreachable code in HTTP handling') async def get_from_cdn(self, url: str) -> bytes: async with self.__session.get(url) as resp: if resp.status == 200: return await resp.read() elif resp.status == 404: raise NotFound(resp, 'asset not found') elif resp.status == 403: raise Forbidden(resp, 'cannot retrieve asset') else: raise HTTPException(resp, 'failed to get asset') # state management async def close(self) -> None: if self.__session: await self.__session.close() # login management async def static_login(self, token: str) -> user.User: # Necessary to get aiohttp to stop complaining about session creation self.__session = aiohttp.ClientSession(connector=self.connector, ws_response_class=DiscordClientWebSocketResponse) old_token = self.token self.token = token try: data = await self.request(Route('GET', '/users/@me')) except HTTPException as exc: self.token = old_token if exc.status == 401: raise LoginFailure('Improper token has been passed.') from exc raise return data def logout(self) -> Response[None]: return self.request(Route('POST', '/auth/logout')) # Group functionality def start_group(self, user_id: Snowflake, recipients: List[int]) -> Response[channel.GroupDMChannel]: payload = { 'recipients': recipients, } return self.request(Route('POST', '/users/{user_id}/channels', user_id=user_id), json=payload) def leave_group(self, channel_id) -> Response[None]: return self.request(Route('DELETE', '/channels/{channel_id}', channel_id=channel_id)) # Message management def start_private_message(self, user_id: Snowflake) -> Response[channel.DMChannel]: payload = { 'recipient_id': user_id, } return self.request(Route('POST', '/users/@me/channels'), json=payload) def send_message( self, channel_id: Snowflake, content: Optional[str], *, tts: bool = False, embed: Optional[embed.Embed] = None, embeds: Optional[List[embed.Embed]] = None, nonce: Optional[str] = None, allowed_mentions: Optional[message.AllowedMentions] = None, message_reference: Optional[message.MessageReference] = None, stickers: Optional[List[sticker.StickerItem]] = None, components: Optional[List[components.Component]] = None, ) -> Response[message.Message]: r = Route('POST', '/channels/{channel_id}/messages', channel_id=channel_id) payload = {} if content: payload['content'] = content if tts: payload['tts'] = True if embed: payload['embeds'] = [embed] if embeds: payload['embeds'] = embeds if nonce: payload['nonce'] = nonce if allowed_mentions: payload['allowed_mentions'] = allowed_mentions if message_reference: payload['message_reference'] = message_reference if components: payload['components'] = components if stickers: payload['sticker_ids'] = stickers return self.request(r, json=payload) def send_typing(self, channel_id: Snowflake) -> Response[None]: return self.request(Route('POST', '/channels/{channel_id}/typing', channel_id=channel_id)) def send_multipart_helper( self, route: Route, *, files: Sequence[File], content: Optional[str] = None, tts: bool = False, embed: Optional[embed.Embed] = None, embeds: Optional[Iterable[Optional[embed.Embed]]] = None, nonce: Optional[str] = None, allowed_mentions: Optional[message.AllowedMentions] = None, message_reference: Optional[message.MessageReference] = None, stickers: Optional[List[sticker.StickerItem]] = None, components: Optional[List[components.Component]] = None, ) -> Response[message.Message]: form = [] payload: Dict[str, Any] = {'tts': tts} if content: payload['content'] = content if embed: payload['embeds'] = [embed] if embeds: payload['embeds'] = embeds if nonce: payload['nonce'] = nonce if allowed_mentions: payload['allowed_mentions'] = allowed_mentions if message_reference: payload['message_reference'] = message_reference if components: payload['components'] = components if stickers: payload['sticker_ids'] = stickers form.append({'name': 'payload_json', 'value': utils._to_json(payload)}) if len(files) == 1: file = files[0] form.append( { 'name': 'file', 'value': file.fp, 'filename': file.filename, 'content_type': 'application/octet-stream', } ) else: for index, file in enumerate(files): form.append( { 'name': f'file{index}', 'value': file.fp, 'filename': file.filename, 'content_type': 'application/octet-stream', } ) return self.request(route, form=form, files=files) def send_files( self, channel_id: Snowflake, *, files: Sequence[File], content: Optional[str] = None, tts: bool = False, embed: Optional[embed.Embed] = None, embeds: Optional[List[embed.Embed]] = None, nonce: Optional[str] = None, allowed_mentions: Optional[message.AllowedMentions] = None, message_reference: Optional[message.MessageReference] = None, stickers: Optional[List[sticker.StickerItem]] = None, components: Optional[List[components.Component]] = None, ) -> Response[message.Message]: r = Route('POST', '/channels/{channel_id}/messages', channel_id=channel_id) return self.send_multipart_helper( r, files=files, content=content, tts=tts, embed=embed, embeds=embeds, nonce=nonce, allowed_mentions=allowed_mentions, message_reference=message_reference, stickers=stickers, components=components, ) def delete_message( self, channel_id: Snowflake, message_id: Snowflake, *, reason: Optional[str] = None ) -> Response[None]: r = Route('DELETE', '/channels/{channel_id}/messages/{message_id}', channel_id=channel_id, message_id=message_id) return self.request(r, reason=reason) def delete_messages( self, channel_id: Snowflake, message_ids: SnowflakeList, *, reason: Optional[str] = None ) -> Response[None]: r = Route('POST', '/channels/{channel_id}/messages/bulk-delete', channel_id=channel_id) payload = { 'messages': message_ids, } return self.request(r, json=payload, reason=reason) def edit_message(self, channel_id: Snowflake, message_id: Snowflake, **fields: Any) -> Response[message.Message]: r = Route('PATCH', '/channels/{channel_id}/messages/{message_id}', channel_id=channel_id, message_id=message_id) return self.request(r, json=fields) def add_reaction(self, channel_id: Snowflake, message_id: Snowflake, emoji: str) -> Response[None]: r = Route( 'PUT', '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/@me', channel_id=channel_id, message_id=message_id, emoji=emoji, ) return self.request(r) def remove_reaction( self, channel_id: Snowflake, message_id: Snowflake, emoji: str, member_id: Snowflake ) -> Response[None]: r = Route( 'DELETE', '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/{member_id}', channel_id=channel_id, message_id=message_id, member_id=member_id, emoji=emoji, ) return self.request(r) def remove_own_reaction(self, channel_id: Snowflake, message_id: Snowflake, emoji: str) -> Response[None]: r = Route( 'DELETE', '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/@me', channel_id=channel_id, message_id=message_id, emoji=emoji, ) return self.request(r) def get_reaction_users( self, channel_id: Snowflake, message_id: Snowflake, emoji: str, limit: int, after: Optional[Snowflake] = None, ) -> Response[List[user.User]]: r = Route( 'GET', '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}', channel_id=channel_id, message_id=message_id, emoji=emoji, ) params: Dict[str, Any] = { 'limit': limit, } if after: params['after'] = after return self.request(r, params=params) def clear_reactions(self, channel_id: Snowflake, message_id: Snowflake) -> Response[None]: r = Route( 'DELETE', '/channels/{channel_id}/messages/{message_id}/reactions', channel_id=channel_id, message_id=message_id, ) return self.request(r) def clear_single_reaction(self, channel_id: Snowflake, message_id: Snowflake, emoji: str) -> Response[None]: r = Route( 'DELETE', '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}', channel_id=channel_id, message_id=message_id, emoji=emoji, ) return self.request(r) def get_message(self, channel_id: Snowflake, message_id: Snowflake) -> Response[message.Message]: r = Route('GET', '/channels/{channel_id}/messages/{message_id}', channel_id=channel_id, message_id=message_id) return self.request(r) def get_channel(self, channel_id: Snowflake) -> Response[channel.Channel]: r = Route('GET', '/channels/{channel_id}', channel_id=channel_id) return self.request(r) def logs_from( self, channel_id: Snowflake, limit: int, before: Optional[Snowflake] = None, after: Optional[Snowflake] = None, around: Optional[Snowflake] = None, ) -> Response[List[message.Message]]: params: Dict[str, Any] = { 'limit': limit, } if before is not None: params['before'] = before if after is not None: params['after'] = after if around is not None: params['around'] = around return self.request(Route('GET', '/channels/{channel_id}/messages', channel_id=channel_id), params=params) def publish_message(self, channel_id: Snowflake, message_id: Snowflake) -> Response[message.Message]: return self.request( Route( 'POST', '/channels/{channel_id}/messages/{message_id}/crosspost', channel_id=channel_id, message_id=message_id, ) ) def pin_message(self, channel_id: Snowflake, message_id: Snowflake, reason: Optional[str] = None) -> Response[None]: r = Route( 'PUT', '/channels/{channel_id}/pins/{message_id}', channel_id=channel_id, message_id=message_id, ) return self.request(r, reason=reason) def unpin_message(self, channel_id: Snowflake, message_id: Snowflake, reason: Optional[str] = None) -> Response[None]: r = Route( 'DELETE', '/channels/{channel_id}/pins/{message_id}', channel_id=channel_id, message_id=message_id, ) return self.request(r, reason=reason) def pins_from(self, channel_id: Snowflake) -> Response[List[message.Message]]: return self.request(Route('GET', '/channels/{channel_id}/pins', channel_id=channel_id)) # Member management def kick(self, user_id: Snowflake, guild_id: Snowflake, reason: Optional[str] = None) -> Response[None]: r = Route('DELETE', '/guilds/{guild_id}/members/{user_id}', guild_id=guild_id, user_id=user_id) if reason: # thanks aiohttp r.url = f'{r.url}?reason={_uriquote(reason)}' return self.request(r) def ban( self, user_id: Snowflake, guild_id: Snowflake, delete_message_days: int = 1, reason: Optional[str] = None, ) -> Response[None]: r = Route('PUT', '/guilds/{guild_id}/bans/{user_id}', guild_id=guild_id, user_id=user_id) params = { 'delete_message_days': delete_message_days, } return self.request(r, params=params, reason=reason) def unban(self, user_id: Snowflake, guild_id: Snowflake, *, reason: Optional[str] = None) -> Response[None]: r = Route('DELETE', '/guilds/{guild_id}/bans/{user_id}', guild_id=guild_id, user_id=user_id) return self.request(r, reason=reason) def guild_voice_state( self, user_id: Snowflake, guild_id: Snowflake, *, mute: Optional[bool] = None, deafen: Optional[bool] = None, reason: Optional[str] = None, ) -> Response[member.Member]: r = Route('PATCH', '/guilds/{guild_id}/members/{user_id}', guild_id=guild_id, user_id=user_id) payload = {} if mute is not None: payload['mute'] = mute if deafen is not None: payload['deaf'] = deafen return self.request(r, json=payload, reason=reason) def edit_profile(self, payload: Dict[str, Any]) -> Response[user.User]: return self.request(Route('PATCH', '/users/@me'), json=payload) def change_my_nickname( self, guild_id: Snowflake, nickname: str, *, reason: Optional[str] = None, ) -> Response[member.Nickname]: r = Route('PATCH', '/guilds/{guild_id}/members/@me/nick', guild_id=guild_id) payload = { 'nick': nickname, } return self.request(r, json=payload, reason=reason) def change_nickname( self, guild_id: Snowflake, user_id: Snowflake, nickname: str, *, reason: Optional[str] = None, ) -> Response[member.Member]: r = Route('PATCH', '/guilds/{guild_id}/members/{user_id}', guild_id=guild_id, user_id=user_id) payload = { 'nick': nickname, } return self.request(r, json=payload, reason=reason) def edit_my_voice_state(self, guild_id: Snowflake, payload: Dict[str, Any]) -> Response[None]: r = Route('PATCH', '/guilds/{guild_id}/voice-states/@me', guild_id=guild_id) return self.request(r, json=payload) def edit_voice_state(self, guild_id: Snowflake, user_id: Snowflake, payload: Dict[str, Any]) -> Response[None]: r = Route('PATCH', '/guilds/{guild_id}/voice-states/{user_id}', guild_id=guild_id, user_id=user_id) return self.request(r, json=payload) def edit_member( self, guild_id: Snowflake, user_id: Snowflake, *, reason: Optional[str] = None, **fields: Any, ) -> Response[member.MemberWithUser]: r = Route('PATCH', '/guilds/{guild_id}/members/{user_id}', guild_id=guild_id, user_id=user_id) return self.request(r, json=fields, reason=reason) # Channel management def edit_channel( self, channel_id: Snowflake, *, reason: Optional[str] = None, **options: Any, ) -> Response[channel.Channel]: r = Route('PATCH', '/channels/{channel_id}', channel_id=channel_id) valid_keys = ( 'name', 'parent_id', 'topic', 'bitrate', 'nsfw', 'user_limit', 'position', 'permission_overwrites', 'rate_limit_per_user', 'type', 'rtc_region', 'video_quality_mode', 'archived', 'auto_archive_duration', 'locked', 'invitable', 'default_auto_archive_duration', ) payload = {k: v for k, v in options.items() if k in valid_keys} return self.request(r, reason=reason, json=payload) def bulk_channel_update( self, guild_id: Snowflake, data: List[guild.ChannelPositionUpdate], *, reason: Optional[str] = None, ) -> Response[None]: r = Route('PATCH', '/guilds/{guild_id}/channels', guild_id=guild_id) return self.request(r, json=data, reason=reason) def create_channel( self, guild_id: Snowflake, channel_type: channel.ChannelType, *, reason: Optional[str] = None, **options: Any, ) -> Response[channel.GuildChannel]: payload = { 'type': channel_type, } valid_keys = ( 'name', 'parent_id', 'topic', 'bitrate', 'nsfw', 'user_limit', 'position', 'permission_overwrites', 'rate_limit_per_user', 'rtc_region', 'video_quality_mode', 'auto_archive_duration', ) payload.update({k: v for k, v in options.items() if k in valid_keys and v is not None}) return self.request(Route('POST', '/guilds/{guild_id}/channels', guild_id=guild_id), json=payload, reason=reason) def delete_channel( self, channel_id: Snowflake, *, reason: Optional[str] = None, ) -> Response[None]: return self.request(Route('DELETE', '/channels/{channel_id}', channel_id=channel_id), reason=reason) # Thread management def start_thread_with_message( self, channel_id: Snowflake, message_id: Snowflake, *, name: str, auto_archive_duration: threads.ThreadArchiveDuration, reason: Optional[str] = None, ) -> Response[threads.Thread]: payload = { 'name': name, 'auto_archive_duration': auto_archive_duration, } route = Route( 'POST', '/channels/{channel_id}/messages/{message_id}/threads', channel_id=channel_id, message_id=message_id ) return self.request(route, json=payload, reason=reason) def start_thread_without_message( self, channel_id: Snowflake, *, name: str, auto_archive_duration: threads.ThreadArchiveDuration, type: threads.ThreadType, invitable: bool = True, reason: Optional[str] = None, ) -> Response[threads.Thread]: payload = { 'name': name, 'auto_archive_duration': auto_archive_duration, 'type': type, 'invitable': invitable, } route = Route('POST', '/channels/{channel_id}/threads', channel_id=channel_id) return self.request(route, json=payload, reason=reason) def join_thread(self, channel_id: Snowflake) -> Response[None]: return self.request(Route('POST', '/channels/{channel_id}/thread-members/@me', channel_id=channel_id)) def add_user_to_thread(self, channel_id: Snowflake, user_id: Snowflake) -> Response[None]: return self.request( Route('PUT', '/channels/{channel_id}/thread-members/{user_id}', channel_id=channel_id, user_id=user_id) ) def leave_thread(self, channel_id: Snowflake) -> Response[None]: return self.request(Route('DELETE', '/channels/{channel_id}/thread-members/@me', channel_id=channel_id)) def remove_user_from_thread(self, channel_id: Snowflake, user_id: Snowflake) -> Response[None]: route = Route('DELETE', '/channels/{channel_id}/thread-members/{user_id}', channel_id=channel_id, user_id=user_id) return self.request(route) def get_public_archived_threads( self, channel_id: Snowflake, before: Optional[Snowflake] = None, limit: int = 50 ) -> Response[threads.ThreadPaginationPayload]: route = Route('GET', '/channels/{channel_id}/threads/archived/public', channel_id=channel_id) params = {} if before: params['before'] = before params['limit'] = limit return self.request(route, params=params) def get_private_archived_threads( self, channel_id: Snowflake, before: Optional[Snowflake] = None, limit: int = 50 ) -> Response[threads.ThreadPaginationPayload]: route = Route('GET', '/channels/{channel_id}/threads/archived/private', channel_id=channel_id) params = {} if before: params['before'] = before params['limit'] = limit return self.request(route, params=params) def get_joined_private_archived_threads( self, channel_id: Snowflake, before: Optional[Snowflake] = None, limit: int = 50 ) -> Response[threads.ThreadPaginationPayload]: route = Route('GET', '/channels/{channel_id}/users/@me/threads/archived/private', channel_id=channel_id) params = {} if before: params['before'] = before params['limit'] = limit return self.request(route, params=params) def get_active_threads(self, guild_id: Snowflake) -> Response[threads.ThreadPaginationPayload]: route = Route('GET', '/guilds/{guild_id}/threads/active', guild_id=guild_id) return self.request(route) def get_thread_members(self, channel_id: Snowflake) -> Response[List[threads.ThreadMember]]: route = Route('GET', '/channels/{channel_id}/thread-members', channel_id=channel_id) return self.request(route) # Webhook management def create_webhook( self, channel_id: Snowflake, *, name: str, avatar: Optional[bytes] = None, reason: Optional[str] = None, ) -> Response[webhook.Webhook]: payload: Dict[str, Any] = { 'name': name, } if avatar is not None: payload['avatar'] = avatar r = Route('POST', '/channels/{channel_id}/webhooks', channel_id=channel_id) return self.request(r, json=payload, reason=reason) def channel_webhooks(self, channel_id: Snowflake) -> Response[List[webhook.Webhook]]: return self.request(Route('GET', '/channels/{channel_id}/webhooks', channel_id=channel_id)) def guild_webhooks(self, guild_id: Snowflake) -> Response[List[webhook.Webhook]]: return self.request(Route('GET', '/guilds/{guild_id}/webhooks', guild_id=guild_id)) def get_webhook(self, webhook_id: Snowflake) -> Response[webhook.Webhook]: return self.request(Route('GET', '/webhooks/{webhook_id}', webhook_id=webhook_id)) def follow_webhook( self, channel_id: Snowflake, webhook_channel_id: Snowflake, reason: Optional[str] = None, ) -> Response[None]: payload = { 'webhook_channel_id': str(webhook_channel_id), } return self.request( Route('POST', '/channels/{channel_id}/followers', channel_id=channel_id), json=payload, reason=reason ) # Guild management def get_guilds( self, limit: int, before: Optional[Snowflake] = None, after: Optional[Snowflake] = None, ) -> Response[List[guild.Guild]]: params: Dict[str, Any] = { 'limit': limit, } if before: params['before'] = before if after: params['after'] = after return self.request(Route('GET', '/users/@me/guilds'), params=params) def leave_guild(self, guild_id: Snowflake) -> Response[None]: return self.request(Route('DELETE', '/users/@me/guilds/{guild_id}', guild_id=guild_id)) def get_guild(self, guild_id: Snowflake) -> Response[guild.Guild]: return self.request(Route('GET', '/guilds/{guild_id}', guild_id=guild_id)) def delete_guild(self, guild_id: Snowflake) -> Response[None]: return self.request(Route('DELETE', '/guilds/{guild_id}', guild_id=guild_id)) def create_guild(self, name: str, region: str, icon: Optional[str]) -> Response[guild.Guild]: payload = { 'name': name, 'region': region, } if icon: payload['icon'] = icon return self.request(Route('POST', '/guilds'), json=payload) def edit_guild(self, guild_id: Snowflake, *, reason: Optional[str] = None, **fields: Any) -> Response[guild.Guild]: valid_keys = ( 'name', 'region', 'icon', 'afk_timeout', 'owner_id', 'afk_channel_id', 'splash', 'discovery_splash', 'features', 'verification_level', 'system_channel_id', 'default_message_notifications', 'description', 'explicit_content_filter', 'banner', 'system_channel_flags', 'rules_channel_id', 'public_updates_channel_id', 'preferred_locale', ) payload = {k: v for k, v in fields.items() if k in valid_keys} return self.request(Route('PATCH', '/guilds/{guild_id}', guild_id=guild_id), json=payload, reason=reason) def get_template(self, code: str) -> Response[template.Template]: return self.request(Route('GET', '/guilds/templates/{code}', code=code)) def guild_templates(self, guild_id: Snowflake) -> Response[List[template.Template]]: return self.request(Route('GET', '/guilds/{guild_id}/templates', guild_id=guild_id)) def create_template(self, guild_id: Snowflake, payload: template.CreateTemplate) -> Response[template.Template]: return self.request(Route('POST', '/guilds/{guild_id}/templates', guild_id=guild_id), json=payload) def sync_template(self, guild_id: Snowflake, code: str) -> Response[template.Template]: return self.request(Route('PUT', '/guilds/{guild_id}/templates/{code}', guild_id=guild_id, code=code)) def edit_template(self, guild_id: Snowflake, code: str, payload) -> Response[template.Template]: valid_keys = ( 'name', 'description', ) payload = {k: v for k, v in payload.items() if k in valid_keys} return self.request( Route('PATCH', '/guilds/{guild_id}/templates/{code}', guild_id=guild_id, code=code), json=payload ) def delete_template(self, guild_id: Snowflake, code: str) -> Response[None]: return self.request(Route('DELETE', '/guilds/{guild_id}/templates/{code}', guild_id=guild_id, code=code)) def create_from_template(self, code: str, name: str, region: str, icon: Optional[str]) -> Response[guild.Guild]: payload = { 'name': name, 'region': region, } if icon: payload['icon'] = icon return self.request(Route('POST', '/guilds/templates/{code}', code=code), json=payload) def get_bans(self, guild_id: Snowflake) -> Response[List[guild.Ban]]: return self.request(Route('GET', '/guilds/{guild_id}/bans', guild_id=guild_id)) def get_ban(self, user_id: Snowflake, guild_id: Snowflake) -> Response[guild.Ban]: return self.request(Route('GET', '/guilds/{guild_id}/bans/{user_id}', guild_id=guild_id, user_id=user_id)) def get_vanity_code(self, guild_id: Snowflake) -> Response[invite.VanityInvite]: return self.request(Route('GET', '/guilds/{guild_id}/vanity-url', guild_id=guild_id)) def change_vanity_code(self, guild_id: Snowflake, code: str, *, reason: Optional[str] = None) -> Response[None]: payload: Dict[str, Any] = {'code': code} return self.request(Route('PATCH', '/guilds/{guild_id}/vanity-url', guild_id=guild_id), json=payload, reason=reason) def get_all_guild_channels(self, guild_id: Snowflake) -> Response[List[guild.GuildChannel]]: return self.request(Route('GET', '/guilds/{guild_id}/channels', guild_id=guild_id)) def get_members( self, guild_id: Snowflake, limit: int, after: Optional[Snowflake] ) -> Response[List[member.MemberWithUser]]: params: Dict[str, Any] = { 'limit': limit, } if after: params['after'] = after r = Route('GET', '/guilds/{guild_id}/members', guild_id=guild_id) return self.request(r, params=params) def get_member(self, guild_id: Snowflake, member_id: Snowflake) -> Response[member.MemberWithUser]: return self.request(Route('GET', '/guilds/{guild_id}/members/{member_id}', guild_id=guild_id, member_id=member_id)) def prune_members( self, guild_id: Snowflake, days: int, compute_prune_count: bool, roles: List[str], *, reason: Optional[str] = None, ) -> Response[guild.GuildPrune]: payload: Dict[str, Any] = { 'days': days, 'compute_prune_count': 'true' if compute_prune_count else 'false', } if roles: payload['include_roles'] = ', '.join(roles) return self.request(Route('POST', '/guilds/{guild_id}/prune', guild_id=guild_id), json=payload, reason=reason) def estimate_pruned_members( self, guild_id: Snowflake, days: int, roles: List[str], ) -> Response[guild.GuildPrune]: params: Dict[str, Any] = { 'days': days, } if roles: params['include_roles'] = ', '.join(roles) return self.request(Route('GET', '/guilds/{guild_id}/prune', guild_id=guild_id), params=params) def get_sticker(self, sticker_id: Snowflake) -> Response[sticker.Sticker]: return self.request(Route('GET', '/stickers/{sticker_id}', sticker_id=sticker_id)) def list_premium_sticker_packs(self) -> Response[sticker.ListPremiumStickerPacks]: return self.request(Route('GET', '/sticker-packs')) def get_all_guild_stickers(self, guild_id: Snowflake) -> Response[List[sticker.GuildSticker]]: return self.request(Route('GET', '/guilds/{guild_id}/stickers', guild_id=guild_id)) def get_guild_sticker(self, guild_id: Snowflake, sticker_id: Snowflake) -> Response[sticker.GuildSticker]: return self.request( Route('GET', '/guilds/{guild_id}/stickers/{sticker_id}', guild_id=guild_id, sticker_id=sticker_id) ) def create_guild_sticker( self, guild_id: Snowflake, payload: sticker.CreateGuildSticker, file: File, reason: str ) -> Response[sticker.GuildSticker]: initial_bytes = file.fp.read(16) try: mime_type = utils._get_mime_type_for_image(initial_bytes) except InvalidArgument: if initial_bytes.startswith(b'{'): mime_type = 'application/json' else: mime_type = 'application/octet-stream' finally: file.reset() form: List[Dict[str, Any]] = [ { 'name': 'file', 'value': file.fp, 'filename': file.filename, 'content_type': mime_type, } ] for k, v in payload.items(): form.append( { 'name': k, 'value': v, } ) return self.request( Route('POST', '/guilds/{guild_id}/stickers', guild_id=guild_id), form=form, files=[file], reason=reason ) def modify_guild_sticker( self, guild_id: Snowflake, sticker_id: Snowflake, payload: sticker.EditGuildSticker, reason: Optional[str], ) -> Response[sticker.GuildSticker]: return self.request( Route('PATCH', '/guilds/{guild_id}/stickers/{sticker_id}', guild_id=guild_id, sticker_id=sticker_id), json=payload, reason=reason, ) def delete_guild_sticker(self, guild_id: Snowflake, sticker_id: Snowflake, reason: Optional[str]) -> Response[None]: return self.request( Route('DELETE', '/guilds/{guild_id}/stickers/{sticker_id}', guild_id=guild_id, sticker_id=sticker_id), reason=reason, ) def get_all_custom_emojis(self, guild_id: Snowflake) -> Response[List[emoji.Emoji]]: return self.request(Route('GET', '/guilds/{guild_id}/emojis', guild_id=guild_id)) def get_custom_emoji(self, guild_id: Snowflake, emoji_id: Snowflake) -> Response[emoji.Emoji]: return self.request(Route('GET', '/guilds/{guild_id}/emojis/{emoji_id}', guild_id=guild_id, emoji_id=emoji_id)) def create_custom_emoji( self, guild_id: Snowflake, name: str, image: bytes, *, roles: Optional[SnowflakeList] = None, reason: Optional[str] = None, ) -> Response[emoji.Emoji]: payload = { 'name': name, 'image': image, 'roles': roles or [], } r = Route('POST', '/guilds/{guild_id}/emojis', guild_id=guild_id) return self.request(r, json=payload, reason=reason) def delete_custom_emoji( self, guild_id: Snowflake, emoji_id: Snowflake, *, reason: Optional[str] = None, ) -> Response[None]: r = Route('DELETE', '/guilds/{guild_id}/emojis/{emoji_id}', guild_id=guild_id, emoji_id=emoji_id) return self.request(r, reason=reason) def edit_custom_emoji( self, guild_id: Snowflake, emoji_id: Snowflake, *, payload: Dict[str, Any], reason: Optional[str] = None, ) -> Response[emoji.Emoji]: r = Route('PATCH', '/guilds/{guild_id}/emojis/{emoji_id}', guild_id=guild_id, emoji_id=emoji_id) return self.request(r, json=payload, reason=reason) def get_all_integrations(self, guild_id: Snowflake) -> Response[List[integration.Integration]]: r = Route('GET', '/guilds/{guild_id}/integrations', guild_id=guild_id) return self.request(r) def create_integration(self, guild_id: Snowflake, type: integration.IntegrationType, id: int) -> Response[None]: payload = { 'type': type, 'id': id, } r = Route('POST', '/guilds/{guild_id}/integrations', guild_id=guild_id) return self.request(r, json=payload) def edit_integration(self, guild_id: Snowflake, integration_id: Snowflake, **payload: Any) -> Response[None]: r = Route( 'PATCH', '/guilds/{guild_id}/integrations/{integration_id}', guild_id=guild_id, integration_id=integration_id ) return self.request(r, json=payload) def sync_integration(self, guild_id: Snowflake, integration_id: Snowflake) -> Response[None]: r = Route( 'POST', '/guilds/{guild_id}/integrations/{integration_id}/sync', guild_id=guild_id, integration_id=integration_id ) return self.request(r) def delete_integration( self, guild_id: Snowflake, integration_id: Snowflake, *, reason: Optional[str] = None ) -> Response[None]: r = Route( 'DELETE', '/guilds/{guild_id}/integrations/{integration_id}', guild_id=guild_id, integration_id=integration_id ) return self.request(r, reason=reason) def get_audit_logs( self, guild_id: Snowflake, limit: int = 100, before: Optional[Snowflake] = None, after: Optional[Snowflake] = None, user_id: Optional[Snowflake] = None, action_type: Optional[AuditLogAction] = None, ) -> Response[audit_log.AuditLog]: params: Dict[str, Any] = {'limit': limit} if before: params['before'] = before if after: params['after'] = after if user_id: params['user_id'] = user_id if action_type: params['action_type'] = action_type r = Route('GET', '/guilds/{guild_id}/audit-logs', guild_id=guild_id) return self.request(r, params=params) def get_widget(self, guild_id: Snowflake) -> Response[widget.Widget]: return self.request(Route('GET', '/guilds/{guild_id}/widget.json', guild_id=guild_id)) def edit_widget(self, guild_id: Snowflake, payload) -> Response[widget.WidgetSettings]: return self.request(Route('PATCH', '/guilds/{guild_id}/widget', guild_id=guild_id), json=payload) # Invite management def create_invite( self, channel_id: Snowflake, *, reason: Optional[str] = None, max_age: int = 0, max_uses: int = 0, temporary: bool = False, unique: bool = True, target_type: Optional[invite.InviteTargetType] = None, target_user_id: Optional[Snowflake] = None, target_application_id: Optional[Snowflake] = None, ) -> Response[invite.Invite]: r = Route('POST', '/channels/{channel_id}/invites', channel_id=channel_id) payload = { 'max_age': max_age, 'max_uses': max_uses, 'temporary': temporary, 'unique': unique, } if target_type: payload['target_type'] = target_type if target_user_id: payload['target_user_id'] = target_user_id if target_application_id: payload['target_application_id'] = str(target_application_id) return self.request(r, reason=reason, json=payload) def get_invite( self, invite_id: str, *, with_counts: bool = True, with_expiration: bool = True ) -> Response[invite.Invite]: params = { 'with_counts': int(with_counts), 'with_expiration': int(with_expiration), } return self.request(Route('GET', '/invites/{invite_id}', invite_id=invite_id), params=params) def invites_from(self, guild_id: Snowflake) -> Response[List[invite.Invite]]: return self.request(Route('GET', '/guilds/{guild_id}/invites', guild_id=guild_id)) def invites_from_channel(self, channel_id: Snowflake) -> Response[List[invite.Invite]]: return self.request(Route('GET', '/channels/{channel_id}/invites', channel_id=channel_id)) def delete_invite(self, invite_id: str, *, reason: Optional[str] = None) -> Response[None]: return self.request(Route('DELETE', '/invites/{invite_id}', invite_id=invite_id), reason=reason) # Role management def get_roles(self, guild_id: Snowflake) -> Response[List[role.Role]]: return self.request(Route('GET', '/guilds/{guild_id}/roles', guild_id=guild_id)) def edit_role( self, guild_id: Snowflake, role_id: Snowflake, *, reason: Optional[str] = None, **fields: Any ) -> Response[role.Role]: r = Route('PATCH', '/guilds/{guild_id}/roles/{role_id}', guild_id=guild_id, role_id=role_id) valid_keys = ('name', 'permissions', 'color', 'hoist', 'mentionable') payload = {k: v for k, v in fields.items() if k in valid_keys} return self.request(r, json=payload, reason=reason) def delete_role(self, guild_id: Snowflake, role_id: Snowflake, *, reason: Optional[str] = None) -> Response[None]: r = Route('DELETE', '/guilds/{guild_id}/roles/{role_id}', guild_id=guild_id, role_id=role_id) return self.request(r, reason=reason) def replace_roles( self, user_id: Snowflake, guild_id: Snowflake, role_ids: List[int], *, reason: Optional[str] = None, ) -> Response[member.MemberWithUser]: return self.edit_member(guild_id=guild_id, user_id=user_id, roles=role_ids, reason=reason) def create_role(self, guild_id: Snowflake, *, reason: Optional[str] = None, **fields: Any) -> Response[role.Role]: r = Route('POST', '/guilds/{guild_id}/roles', guild_id=guild_id) return self.request(r, json=fields, reason=reason) def move_role_position( self, guild_id: Snowflake, positions: List[guild.RolePositionUpdate], *, reason: Optional[str] = None, ) -> Response[List[role.Role]]: r = Route('PATCH', '/guilds/{guild_id}/roles', guild_id=guild_id) return self.request(r, json=positions, reason=reason) def add_role( self, guild_id: Snowflake, user_id: Snowflake, role_id: Snowflake, *, reason: Optional[str] = None ) -> Response[None]: r = Route( 'PUT', '/guilds/{guild_id}/members/{user_id}/roles/{role_id}', guild_id=guild_id, user_id=user_id, role_id=role_id, ) return self.request(r, reason=reason) def remove_role( self, guild_id: Snowflake, user_id: Snowflake, role_id: Snowflake, *, reason: Optional[str] = None ) -> Response[None]: r = Route( 'DELETE', '/guilds/{guild_id}/members/{user_id}/roles/{role_id}', guild_id=guild_id, user_id=user_id, role_id=role_id, ) return self.request(r, reason=reason) def edit_channel_permissions( self, channel_id: Snowflake, target: Snowflake, allow: str, deny: str, type: channel.OverwriteType, *, reason: Optional[str] = None, ) -> Response[None]: payload = {'id': target, 'allow': allow, 'deny': deny, 'type': type} r = Route('PUT', '/channels/{channel_id}/permissions/{target}', channel_id=channel_id, target=target) return self.request(r, json=payload, reason=reason) def delete_channel_permissions( self, channel_id: Snowflake, target: channel.OverwriteType, *, reason: Optional[str] = None ) -> Response[None]: r = Route('DELETE', '/channels/{channel_id}/permissions/{target}', channel_id=channel_id, target=target) return self.request(r, reason=reason) # Voice management def move_member( self, user_id: Snowflake, guild_id: Snowflake, channel_id: Snowflake, *, reason: Optional[str] = None, ) -> Response[member.MemberWithUser]: return self.edit_member(guild_id=guild_id, user_id=user_id, channel_id=channel_id, reason=reason) # Stage instance management def get_stage_instance(self, channel_id: Snowflake) -> Response[channel.StageInstance]: return self.request(Route('GET', '/stage-instances/{channel_id}', channel_id=channel_id)) def create_stage_instance(self, *, reason: Optional[str], **payload: Any) -> Response[channel.StageInstance]: valid_keys = ( 'channel_id', 'topic', 'privacy_level', ) payload = {k: v for k, v in payload.items() if k in valid_keys} return self.request(Route('POST', '/stage-instances'), json=payload, reason=reason) def edit_stage_instance(self, channel_id: Snowflake, *, reason: Optional[str] = None, **payload: Any) -> Response[None]: valid_keys = ( 'topic', 'privacy_level', ) payload = {k: v for k, v in payload.items() if k in valid_keys} return self.request( Route('PATCH', '/stage-instances/{channel_id}', channel_id=channel_id), json=payload, reason=reason ) def delete_stage_instance(self, channel_id: Snowflake, *, reason: Optional[str] = None) -> Response[None]: return self.request(Route('DELETE', '/stage-instances/{channel_id}', channel_id=channel_id), reason=reason) # Application commands (global) def get_global_commands(self, application_id: Snowflake) -> Response[List[interactions.ApplicationCommand]]: return self.request(Route('GET', '/applications/{application_id}/commands', application_id=application_id)) def get_global_command( self, application_id: Snowflake, command_id: Snowflake ) -> Response[interactions.ApplicationCommand]: r = Route( 'GET', '/applications/{application_id}/commands/{command_id}', application_id=application_id, command_id=command_id, ) return self.request(r) def upsert_global_command(self, application_id: Snowflake, payload) -> Response[interactions.ApplicationCommand]: r = Route('POST', '/applications/{application_id}/commands', application_id=application_id) return self.request(r, json=payload) def edit_global_command( self, application_id: Snowflake, command_id: Snowflake, payload: interactions.EditApplicationCommand, ) -> Response[interactions.ApplicationCommand]: valid_keys = ( 'name', 'description', 'options', ) payload = {k: v for k, v in payload.items() if k in valid_keys} # type: ignore r = Route( 'PATCH', '/applications/{application_id}/commands/{command_id}', application_id=application_id, command_id=command_id, ) return self.request(r, json=payload) def delete_global_command(self, application_id: Snowflake, command_id: Snowflake) -> Response[None]: r = Route( 'DELETE', '/applications/{application_id}/commands/{command_id}', application_id=application_id, command_id=command_id, ) return self.request(r) def bulk_upsert_global_commands( self, application_id: Snowflake, payload ) -> Response[List[interactions.ApplicationCommand]]: r = Route('PUT', '/applications/{application_id}/commands', application_id=application_id) return self.request(r, json=payload) # Application commands (guild) def get_guild_commands( self, application_id: Snowflake, guild_id: Snowflake ) -> Response[List[interactions.ApplicationCommand]]: r = Route( 'GET', '/applications/{application_id}/guilds/{guild_id}/commands', application_id=application_id, guild_id=guild_id, ) return self.request(r) def get_guild_command( self, application_id: Snowflake, guild_id: Snowflake, command_id: Snowflake, ) -> Response[interactions.ApplicationCommand]: r = Route( 'GET', '/applications/{application_id}/guilds/{guild_id}/commands/{command_id}', application_id=application_id, guild_id=guild_id, command_id=command_id, ) return self.request(r) def upsert_guild_command( self, application_id: Snowflake, guild_id: Snowflake, payload: interactions.EditApplicationCommand, ) -> Response[interactions.ApplicationCommand]: r = Route( 'POST', '/applications/{application_id}/guilds/{guild_id}/commands', application_id=application_id, guild_id=guild_id, ) return self.request(r, json=payload) def edit_guild_command( self, application_id: Snowflake, guild_id: Snowflake, command_id: Snowflake, payload: interactions.EditApplicationCommand, ) -> Response[interactions.ApplicationCommand]: valid_keys = ( 'name', 'description', 'options', ) payload = {k: v for k, v in payload.items() if k in valid_keys} # type: ignore r = Route( 'PATCH', '/applications/{application_id}/guilds/{guild_id}/commands/{command_id}', application_id=application_id, guild_id=guild_id, command_id=command_id, ) return self.request(r, json=payload) def delete_guild_command( self, application_id: Snowflake, guild_id: Snowflake, command_id: Snowflake, ) -> Response[None]: r = Route( 'DELETE', '/applications/{application_id}/guilds/{guild_id}/commands/{command_id}', application_id=application_id, guild_id=guild_id, command_id=command_id, ) return self.request(r) def bulk_upsert_guild_commands( self, application_id: Snowflake, guild_id: Snowflake, payload: List[interactions.EditApplicationCommand], ) -> Response[List[interactions.ApplicationCommand]]: r = Route( 'PUT', '/applications/{application_id}/guilds/{guild_id}/commands', application_id=application_id, guild_id=guild_id, ) return self.request(r, json=payload) # Interaction responses def _edit_webhook_helper( self, route: Route, file: Optional[File] = None, content: Optional[str] = None, embeds: Optional[List[embed.Embed]] = None, allowed_mentions: Optional[message.AllowedMentions] = None, ): payload: Dict[str, Any] = {} if content: payload['content'] = content if embeds: payload['embeds'] = embeds if allowed_mentions: payload['allowed_mentions'] = allowed_mentions form: List[Dict[str, Any]] = [ { 'name': 'payload_json', 'value': utils._to_json(payload), } ] if file: form.append( { 'name': 'file', 'value': file.fp, 'filename': file.filename, 'content_type': 'application/octet-stream', } ) return self.request(route, form=form, files=[file] if file else None) def create_interaction_response( self, interaction_id: Snowflake, token: str, *, type: InteractionResponseType, data: Optional[interactions.InteractionApplicationCommandCallbackData] = None, ) -> Response[None]: r = Route( 'POST', '/interactions/{interaction_id}/{interaction_token}/callback', interaction_id=interaction_id, interaction_token=token, ) payload: Dict[str, Any] = { 'type': type, } if data is not None: payload['data'] = data return self.request(r, json=payload) def get_original_interaction_response( self, application_id: Snowflake, token: str, ) -> Response[message.Message]: r = Route( 'GET', '/webhooks/{application_id}/{interaction_token}/messages/@original', application_id=application_id, interaction_token=token, ) return self.request(r) def edit_original_interaction_response( self, application_id: Snowflake, token: str, file: Optional[File] = None, content: Optional[str] = None, embeds: Optional[List[embed.Embed]] = None, allowed_mentions: Optional[message.AllowedMentions] = None, ) -> Response[message.Message]: r = Route( 'PATCH', '/webhooks/{application_id}/{interaction_token}/messages/@original', application_id=application_id, interaction_token=token, ) return self._edit_webhook_helper(r, file=file, content=content, embeds=embeds, allowed_mentions=allowed_mentions) def delete_original_interaction_response(self, application_id: Snowflake, token: str) -> Response[None]: r = Route( 'DELETE', '/webhooks/{application_id}/{interaction_token}/messages/@original', application_id=application_id, interaction_token=token, ) return self.request(r) def create_followup_message( self, application_id: Snowflake, token: str, files: List[File] = [], content: Optional[str] = None, tts: bool = False, embeds: Optional[List[embed.Embed]] = None, allowed_mentions: Optional[message.AllowedMentions] = None, ) -> Response[message.Message]: r = Route( 'POST', '/webhooks/{application_id}/{interaction_token}', application_id=application_id, interaction_token=token, ) return self.send_multipart_helper( r, content=content, files=files, tts=tts, embeds=embeds, allowed_mentions=allowed_mentions, ) def edit_followup_message( self, application_id: Snowflake, token: str, message_id: Snowflake, file: Optional[File] = None, content: Optional[str] = None, embeds: Optional[List[embed.Embed]] = None, allowed_mentions: Optional[message.AllowedMentions] = None, ) -> Response[message.Message]: r = Route( 'PATCH', '/webhooks/{application_id}/{interaction_token}/messages/{message_id}', application_id=application_id, interaction_token=token, message_id=message_id, ) return self._edit_webhook_helper(r, file=file, content=content, embeds=embeds, allowed_mentions=allowed_mentions) def delete_followup_message(self, application_id: Snowflake, token: str, message_id: Snowflake) -> Response[None]: r = Route( 'DELETE', '/webhooks/{application_id}/{interaction_token}/messages/{message_id}', application_id=application_id, interaction_token=token, message_id=message_id, ) return self.request(r) def get_guild_application_command_permissions( self, application_id: Snowflake, guild_id: Snowflake, ) -> Response[List[interactions.GuildApplicationCommandPermissions]]: r = Route( 'GET', '/applications/{application_id}/guilds/{guild_id}/commands/permissions', application_id=application_id, guild_id=guild_id, ) return self.request(r) def get_application_command_permissions( self, application_id: Snowflake, guild_id: Snowflake, command_id: Snowflake, ) -> Response[interactions.GuildApplicationCommandPermissions]: r = Route( 'GET', '/applications/{application_id}/guilds/{guild_id}/commands/{command_id}/permissions', application_id=application_id, guild_id=guild_id, command_id=command_id, ) return self.request(r) def edit_application_command_permissions( self, application_id: Snowflake, guild_id: Snowflake, command_id: Snowflake, payload: interactions.BaseGuildApplicationCommandPermissions, ) -> Response[None]: r = Route( 'PUT', '/applications/{application_id}/guilds/{guild_id}/commands/{command_id}/permissions', application_id=application_id, guild_id=guild_id, command_id=command_id, ) return self.request(r, json=payload) def bulk_edit_guild_application_command_permissions( self, application_id: Snowflake, guild_id: Snowflake, payload: List[interactions.PartialGuildApplicationCommandPermissions], ) -> Response[None]: r = Route( 'PUT', '/applications/{application_id}/guilds/{guild_id}/commands/permissions', application_id=application_id, guild_id=guild_id, ) return self.request(r, json=payload) # Misc def application_info(self) -> Response[appinfo.AppInfo]: return self.request(Route('GET', '/oauth2/applications/@me')) async def get_gateway(self, *, encoding: str = 'json', zlib: bool = True) -> str: try: data = await self.request(Route('GET', '/gateway')) except HTTPException as exc: raise GatewayNotFound() from exc if zlib: value = '{0}?encoding={1}&v=9&compress=zlib-stream' else: value = '{0}?encoding={1}&v=9' return value.format(data['url'], encoding) async def get_bot_gateway(self, *, encoding: str = 'json', zlib: bool = True) -> Tuple[int, str]: try: data = await self.request(Route('GET', '/gateway/bot')) except HTTPException as exc: raise GatewayNotFound() from exc if zlib: value = '{0}?encoding={1}&v=9&compress=zlib-stream' else: value = '{0}?encoding={1}&v=9' return data['shards'], value.format(data['url'], encoding) def get_user(self, user_id: Snowflake) -> Response[user.User]: return self.request(Route('GET', '/users/{user_id}', user_id=user_id))
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/http.py
http.py
from __future__ import annotations import asyncio import datetime import re import io from os import PathLike from typing import Dict, TYPE_CHECKING, Union, List, Optional, Any, Callable, Tuple, ClassVar, Optional, overload, TypeVar, Type from . import utils from .reaction import Reaction from .emoji import Emoji from .partial_emoji import PartialEmoji from .enums import MessageType, ChannelType, try_enum from .errors import InvalidArgument, HTTPException from .components import _component_factory from .embeds import Embed from .member import Member from .flags import MessageFlags from .file import File from .utils import escape_mentions, MISSING from .guild import Guild from .mixins import Hashable from .sticker import StickerItem from .threads import Thread if TYPE_CHECKING: from .types.message import ( Message as MessagePayload, Attachment as AttachmentPayload, MessageReference as MessageReferencePayload, MessageApplication as MessageApplicationPayload, MessageActivity as MessageActivityPayload, Reaction as ReactionPayload, ) from .types.components import Component as ComponentPayload from .types.threads import ThreadArchiveDuration from .types.member import ( Member as MemberPayload, UserWithMember as UserWithMemberPayload, ) from .types.user import User as UserPayload from .types.embed import Embed as EmbedPayload from .abc import Snowflake from .abc import GuildChannel, PartialMessageableChannel, MessageableChannel from .components import Component from .state import ConnectionState from .channel import TextChannel, GroupChannel, DMChannel, PartialMessageable from .mentions import AllowedMentions from .user import User from .role import Role from .ui.view import View MR = TypeVar('MR', bound='MessageReference') EmojiInputType = Union[Emoji, PartialEmoji, str] __all__ = ( 'Attachment', 'Message', 'PartialMessage', 'MessageReference', 'DeletedReferencedMessage', ) 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__}.') class Attachment(Hashable): """Represents an attachment from Discord. .. container:: operations .. describe:: str(x) Returns the URL of the attachment. .. describe:: x == y Checks if the attachment is equal to another attachment. .. describe:: x != y Checks if the attachment is not equal to another attachment. .. describe:: hash(x) Returns the hash of the attachment. .. versionchanged:: 1.7 Attachment can now be casted to :class:`str` and is hashable. Attributes ------------ id: :class:`int` The attachment ID. size: :class:`int` The attachment size in bytes. height: Optional[:class:`int`] The attachment's height, in pixels. Only applicable to images and videos. width: Optional[:class:`int`] The attachment's width, in pixels. Only applicable to images and videos. filename: :class:`str` The attachment's filename. url: :class:`str` The attachment URL. If the message this attachment was attached to is deleted, then this will 404. proxy_url: :class:`str` The proxy URL. This is a cached version of the :attr:`~Attachment.url` in the case of images. When the message is deleted, this URL might be valid for a few minutes or not valid at all. content_type: Optional[:class:`str`] The attachment's `media type <https://en.wikipedia.org/wiki/Media_type>`_ .. versionadded:: 1.7 """ __slots__ = ('id', 'size', 'height', 'width', 'filename', 'url', 'proxy_url', '_http', 'content_type') def __init__(self, *, data: AttachmentPayload, state: ConnectionState): self.id: int = int(data['id']) self.size: int = data['size'] self.height: Optional[int] = data.get('height') self.width: Optional[int] = data.get('width') self.filename: str = data['filename'] self.url: str = data.get('url') self.proxy_url: str = data.get('proxy_url') self._http = state.http self.content_type: Optional[str] = data.get('content_type') def is_spoiler(self) -> bool: """:class:`bool`: Whether this attachment contains a spoiler.""" return self.filename.startswith('SPOILER_') def __repr__(self) -> str: return f'<Attachment id={self.id} filename={self.filename!r} url={self.url!r}>' def __str__(self) -> str: return self.url or '' async def save( self, fp: Union[io.BufferedIOBase, PathLike], *, seek_begin: bool = True, use_cached: bool = False, ) -> int: """|coro| Saves this attachment into a file-like object. Parameters ----------- fp: Union[:class:`io.BufferedIOBase`, :class:`os.PathLike`] The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead. seek_begin: :class:`bool` Whether to seek to the beginning of the file after saving is successfully done. use_cached: :class:`bool` Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments. Raises -------- HTTPException Saving the attachment failed. NotFound The attachment was deleted. Returns -------- :class:`int` The number of bytes written. """ data = await self.read(use_cached=use_cached) if isinstance(fp, io.BufferedIOBase): written = fp.write(data) if seek_begin: fp.seek(0) return written else: with open(fp, 'wb') as f: return f.write(data) async def read(self, *, use_cached: bool = False) -> bytes: """|coro| Retrieves the content of this attachment as a :class:`bytes` object. .. versionadded:: 1.1 Parameters ----------- use_cached: :class:`bool` Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments. Raises ------ HTTPException Downloading the attachment failed. Forbidden You do not have permissions to access this attachment NotFound The attachment was deleted. Returns ------- :class:`bytes` The contents of the attachment. """ url = self.proxy_url if use_cached else self.url data = await self._http.get_from_cdn(url) return data async def to_file(self, *, use_cached: bool = False, spoiler: bool = False) -> File: """|coro| Converts the attachment into a :class:`File` suitable for sending via :meth:`abc.Messageable.send`. .. versionadded:: 1.3 Parameters ----------- use_cached: :class:`bool` Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments. .. versionadded:: 1.4 spoiler: :class:`bool` Whether the file is a spoiler. .. versionadded:: 1.4 Raises ------ HTTPException Downloading the attachment failed. Forbidden You do not have permissions to access this attachment NotFound The attachment was deleted. Returns ------- :class:`File` The attachment as a file suitable for sending. """ data = await self.read(use_cached=use_cached) return File(io.BytesIO(data), filename=self.filename, spoiler=spoiler) def to_dict(self) -> AttachmentPayload: result: AttachmentPayload = { 'filename': self.filename, 'id': self.id, 'proxy_url': self.proxy_url, 'size': self.size, 'url': self.url, 'spoiler': self.is_spoiler(), } if self.height: result['height'] = self.height if self.width: result['width'] = self.width if self.content_type: result['content_type'] = self.content_type return result class DeletedReferencedMessage: """A special sentinel type that denotes whether the resolved message referenced message had since been deleted. The purpose of this class is to separate referenced messages that could not be fetched and those that were previously fetched but have since been deleted. .. versionadded:: 1.6 """ __slots__ = ('_parent',) def __init__(self, parent: MessageReference): self._parent: MessageReference = parent def __repr__(self) -> str: return f"<DeletedReferencedMessage id={self.id} channel_id={self.channel_id} guild_id={self.guild_id!r}>" @property def id(self) -> int: """:class:`int`: The message ID of the deleted referenced message.""" # the parent's message id won't be None here return self._parent.message_id # type: ignore @property def channel_id(self) -> int: """:class:`int`: The channel ID of the deleted referenced message.""" return self._parent.channel_id @property def guild_id(self) -> Optional[int]: """Optional[:class:`int`]: The guild ID of the deleted referenced message.""" return self._parent.guild_id class MessageReference: """Represents a reference to a :class:`~discord.Message`. .. versionadded:: 1.5 .. versionchanged:: 1.6 This class can now be constructed by users. Attributes ----------- message_id: Optional[:class:`int`] The id of the message referenced. channel_id: :class:`int` The channel id of the message referenced. guild_id: Optional[:class:`int`] The guild id of the message referenced. fail_if_not_exists: :class:`bool` Whether replying to the referenced message should raise :class:`HTTPException` if the message no longer exists or Discord could not fetch the message. .. versionadded:: 1.7 resolved: Optional[Union[:class:`Message`, :class:`DeletedReferencedMessage`]] The message that this reference resolved to. If this is ``None`` then the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. If the message was resolved at a prior point but has since been deleted then this will be of type :class:`DeletedReferencedMessage`. Currently, this is mainly the replied to message when a user replies to a message. .. versionadded:: 1.6 """ __slots__ = ('message_id', 'channel_id', 'guild_id', 'fail_if_not_exists', 'resolved', '_state') def __init__(self, *, message_id: int, channel_id: int, guild_id: Optional[int] = None, fail_if_not_exists: bool = True): self._state: Optional[ConnectionState] = None self.resolved: Optional[Union[Message, DeletedReferencedMessage]] = None self.message_id: Optional[int] = message_id self.channel_id: int = channel_id self.guild_id: Optional[int] = guild_id self.fail_if_not_exists: bool = fail_if_not_exists @classmethod def with_state(cls: Type[MR], state: ConnectionState, data: MessageReferencePayload) -> MR: self = cls.__new__(cls) self.message_id = utils._get_as_snowflake(data, 'message_id') self.channel_id = int(data.pop('channel_id')) self.guild_id = utils._get_as_snowflake(data, 'guild_id') self.fail_if_not_exists = data.get('fail_if_not_exists', True) self._state = state self.resolved = None return self @classmethod def from_message(cls: Type[MR], message: Message, *, fail_if_not_exists: bool = True) -> MR: """Creates a :class:`MessageReference` from an existing :class:`~discord.Message`. .. versionadded:: 1.6 Parameters ---------- message: :class:`~discord.Message` The message to be converted into a reference. fail_if_not_exists: :class:`bool` Whether replying to the referenced message should raise :class:`HTTPException` if the message no longer exists or Discord could not fetch the message. .. versionadded:: 1.7 Returns ------- :class:`MessageReference` A reference to the message. """ self = cls( message_id=message.id, channel_id=message.channel.id, guild_id=getattr(message.guild, 'id', None), fail_if_not_exists=fail_if_not_exists, ) self._state = message._state return self @property def cached_message(self) -> Optional[Message]: """Optional[:class:`~discord.Message`]: The cached message, if found in the internal message cache.""" return self._state and self._state._get_message(self.message_id) @property def jump_url(self) -> str: """:class:`str`: Returns a URL that allows the client to jump to the referenced message. .. versionadded:: 1.7 """ guild_id = self.guild_id if self.guild_id is not None else '@me' return f'https://discord.com/channels/{guild_id}/{self.channel_id}/{self.message_id}' def __repr__(self) -> str: return f'<MessageReference message_id={self.message_id!r} channel_id={self.channel_id!r} guild_id={self.guild_id!r}>' def to_dict(self) -> MessageReferencePayload: result: MessageReferencePayload = {'message_id': self.message_id} if self.message_id is not None else {} result['channel_id'] = self.channel_id if self.guild_id is not None: result['guild_id'] = self.guild_id if self.fail_if_not_exists is not None: result['fail_if_not_exists'] = self.fail_if_not_exists return result to_message_reference_dict = to_dict 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 @flatten_handlers 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:`~discord.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. """ __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', 'mentions', 'author', 'attachments', 'nonce', 'pinned', 'role_mentions', 'type', 'flags', 'reactions', 'reference', 'application', 'activity', 'stickers', 'components', '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, ): 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', [])] try: # if the channel doesn't have a guild attribute, we handle that self.guild = channel.guild # type: ignore except AttributeError: self.guild = state._get_guild(utils._get_as_snowflake(data, 'guild_id')) 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 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, user_id) -> Reaction: reaction = utils.find(lambda r: r.emoji == emoji, 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): if str(reaction.emoji) == to_check: break else: # didn't find anything so just return return del self.reactions[index] return reaction def _update(self, data): # 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: try: delattr(self, attr) except AttributeError: pass 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]): self.components = [_component_factory(d) for d in components] def _rebind_cached_references(self, new_guild: Guild, new_channel: Union[TextChannel, Thread]) -> None: self.guild = new_guild self.channel = new_channel @utils.cached_slot_property('_cs_raw_mentions') 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 [int(x) for x in re.findall(r'<@!?([0-9]{15,20})>', self.content)] @utils.cached_slot_property('_cs_raw_channel_mentions') 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 [int(x) for x in re.findall(r'<#([0-9]{15,20})>', self.content)] @utils.cached_slot_property('_cs_raw_role_mentions') 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 [int(x) for x in re.findall(r'<@&([0-9]{15,20})>', self.content)] @utils.cached_slot_property('_cs_channel_mentions') 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) @utils.cached_slot_property('_cs_clean_content') 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. """ # fmt: off 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) # fmt: on 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) @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: The message's creation time in UTC.""" return utils.snowflake_time(self.id) @property 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 @property 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 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.application_command, MessageType.thread_starter_message, ) @utils.cached_slot_property('_cs_system_content') 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.' else: 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.' else: 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!' else: 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!**' else: 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!**' else: 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!**' else: 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!' 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): await asyncio.sleep(delay) try: await self._state.http.delete_message(self.channel.id, self.id) except HTTPException: pass asyncio.create_task(delete(delay)) else: await self._state.http.delete_message(self.channel.id, self.id) @overload 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] = ..., ) -> Message: ... @overload 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] = ..., ) -> 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, ) -> 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. If ``[]`` is passed then all attachments are removed. 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:`~discord.AllowedMentions`] Controls the mentions being processed in this message. If this is passed, then the object is merged with :attr:`~discord.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:`~discord.Client.allowed_mentions`. If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions` are used instead. .. versionadded:: 1.4 view: Optional[:class:`~discord.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 Tried to suppress a message without permissions or edited a message's content or embed that isn't yours. ~discord.InvalidArgument You specified both ``embed`` and ``embeds`` """ 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 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() else: if 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'] = [] 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(): 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:`~discord.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 -------- ~discord.HTTPException Sending the message failed. ~discord.Forbidden You do not have the proper permissions to send the message. ~discord.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:`~discord.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:`~discord.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 PartialMessage(Hashable): """Represents a partial message to aid with working messages when only a message and channel ID are present. There are two ways to construct this class. The first one is through the constructor itself, and the second is via the following: - :meth:`TextChannel.get_partial_message` - :meth:`Thread.get_partial_message` - :meth:`DMChannel.get_partial_message` Note that this class is trimmed down and has no rich attributes. .. versionadded:: 1.6 .. container:: operations .. describe:: x == y Checks if two partial messages are equal. .. describe:: x != y Checks if two partial messages are not equal. .. describe:: hash(x) Returns the partial message's hash. Attributes ----------- channel: Union[:class:`TextChannel`, :class:`Thread`, :class:`DMChannel`] The channel associated with this partial message. id: :class:`int` The message ID. """ __slots__ = ('channel', 'id', '_cs_guild', '_state') jump_url: str = Message.jump_url # type: ignore delete = Message.delete publish = Message.publish pin = Message.pin unpin = Message.unpin add_reaction = Message.add_reaction remove_reaction = Message.remove_reaction clear_reaction = Message.clear_reaction clear_reactions = Message.clear_reactions reply = Message.reply to_reference = Message.to_reference to_message_reference_dict = Message.to_message_reference_dict def __init__(self, *, channel: PartialMessageableChannel, id: int): if channel.type not in ( ChannelType.text, ChannelType.news, ChannelType.private, ChannelType.news_thread, ChannelType.public_thread, ChannelType.private_thread, ): raise TypeError(f'Expected TextChannel, DMChannel or Thread not {type(channel)!r}') self.channel: PartialMessageableChannel = channel self._state: ConnectionState = channel._state self.id: int = id def _update(self, data) -> None: # This is used for duck typing purposes. # Just do nothing with the data. pass # Also needed for duck typing purposes # n.b. not exposed pinned = property(None, lambda x, y: None) def __repr__(self) -> str: return f'<PartialMessage id={self.id} channel={self.channel!r}>' @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: The partial message's creation time in UTC.""" return utils.snowflake_time(self.id) @utils.cached_slot_property('_cs_guild') def guild(self) -> Optional[Guild]: """Optional[:class:`Guild`]: The guild that the partial message belongs to, if applicable.""" return getattr(self.channel, 'guild', None) async def fetch(self) -> Message: """|coro| Fetches the partial message to a full :class:`Message`. Raises -------- NotFound The message was not found. Forbidden You do not have the permissions required to get a message. HTTPException Retrieving the message failed. Returns -------- :class:`Message` The full message. """ data = await self._state.http.get_message(self.channel.id, self.id) return self._state.create_message(channel=self.channel, data=data) async def edit(self, **fields: Any) -> Optional[Message]: """|coro| Edits the message. The content must be able to be transformed into a string via ``str(content)``. .. versionchanged:: 1.7 :class:`discord.Message` is returned instead of ``None`` if an edit took place. 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. 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:`~discord.AllowedMentions`] Controls the mentions being processed in this message. If this is passed, then the object is merged with :attr:`~discord.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:`~discord.Client.allowed_mentions`. If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions` are used instead. view: Optional[:class:`~discord.ui.View`] The updated view to update this message with. If ``None`` is passed then the view is removed. .. versionadded:: 2.0 Raises ------- NotFound The message was not found. HTTPException Editing the message failed. Forbidden Tried to suppress a message without permissions or edited a message's content or embed that isn't yours. Returns --------- Optional[:class:`Message`] The message that was edited. """ try: content = fields['content'] except KeyError: pass else: if content is not None: fields['content'] = str(content) try: embed = fields['embed'] except KeyError: pass else: if embed is not None: fields['embed'] = embed.to_dict() try: suppress: bool = fields.pop('suppress') except KeyError: pass else: flags = MessageFlags._from_value(0) flags.suppress_embeds = suppress fields['flags'] = flags.value delete_after = fields.pop('delete_after', None) try: allowed_mentions = fields.pop('allowed_mentions') except KeyError: pass else: if allowed_mentions is not None: if self._state.allowed_mentions is not None: allowed_mentions = self._state.allowed_mentions.merge(allowed_mentions).to_dict() else: allowed_mentions = allowed_mentions.to_dict() fields['allowed_mentions'] = allowed_mentions try: view = fields.pop('view') except KeyError: # To check for the view afterwards view = None else: self._state.prevent_view_updates_for(self.id) if view: fields['components'] = view.to_components() else: fields['components'] = [] if fields: data = await self._state.http.edit_message(self.channel.id, self.id, **fields) if delete_after is not None: await self.delete(delay=delete_after) if fields: # data isn't unbound msg = self._state.create_message(channel=self.channel, data=data) # type: ignore if view and not view.is_finished(): self._state.store_view(view, self.id) return msg
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/message.py
message.py
from __future__ import annotations from typing import Optional, TYPE_CHECKING from .utils import MISSING, cached_slot_property from .mixins import Hashable from .errors import InvalidArgument from .enums import StagePrivacyLevel, try_enum __all__ = ( 'StageInstance', ) if TYPE_CHECKING: from .types.channel import StageInstance as StageInstancePayload from .state import ConnectionState from .channel import StageChannel from .guild import Guild class StageInstance(Hashable): """Represents a stage instance of a stage channel in a guild. .. versionadded:: 2.0 .. container:: operations .. describe:: x == y Checks if two stage instances are equal. .. describe:: x != y Checks if two stage instances are not equal. .. describe:: hash(x) Returns the stage instance's hash. Attributes ----------- id: :class:`int` The stage instance's ID. guild: :class:`Guild` The guild that the stage instance is running in. channel_id: :class:`int` The ID of the channel that the stage instance is running in. topic: :class:`str` The topic of the stage instance. privacy_level: :class:`StagePrivacyLevel` The privacy level of the stage instance. discoverable_disabled: :class:`bool` Whether discoverability for the stage instance is disabled. """ __slots__ = ( '_state', 'id', 'guild', 'channel_id', 'topic', 'privacy_level', 'discoverable_disabled', '_cs_channel', ) def __init__(self, *, state: ConnectionState, guild: Guild, data: StageInstancePayload) -> None: self._state = state self.guild = guild self._update(data) def _update(self, data: StageInstancePayload): self.id: int = int(data['id']) self.channel_id: int = int(data['channel_id']) self.topic: str = data['topic'] self.privacy_level: StagePrivacyLevel = try_enum(StagePrivacyLevel, data['privacy_level']) self.discoverable_disabled: bool = data.get('discoverable_disabled', False) def __repr__(self) -> str: return f'<StageInstance id={self.id} guild={self.guild!r} channel_id={self.channel_id} topic={self.topic!r}>' @cached_slot_property('_cs_channel') def channel(self) -> Optional[StageChannel]: """Optional[:class:`StageChannel`]: The channel that stage instance is running in.""" # the returned channel will always be a StageChannel or None return self._state.get_channel(self.channel_id) # type: ignore def is_public(self) -> bool: return self.privacy_level is StagePrivacyLevel.public async def edit(self, *, topic: str = MISSING, privacy_level: StagePrivacyLevel = MISSING, reason: Optional[str] = None) -> None: """|coro| Edits the stage instance. You must have the :attr:`~Permissions.manage_channels` permission to use this. Parameters ----------- topic: :class:`str` The stage instance's new topic. privacy_level: :class:`StagePrivacyLevel` The stage instance's new privacy level. reason: :class:`str` The reason the stage instance was edited. Shows up on the audit log. Raises ------ InvalidArgument If the ``privacy_level`` parameter is not the proper type. Forbidden You do not have permissions to edit the stage instance. HTTPException Editing a stage instance failed. """ payload = {} if topic is not MISSING: payload['topic'] = topic if privacy_level is not MISSING: if not isinstance(privacy_level, StagePrivacyLevel): raise InvalidArgument('privacy_level field must be of type PrivacyLevel') payload['privacy_level'] = privacy_level.value if payload: await self._state.http.edit_stage_instance(self.channel_id, **payload, reason=reason) async def delete(self, *, reason: Optional[str] = None) -> None: """|coro| Deletes the stage instance. You must have the :attr:`~Permissions.manage_channels` permission to use this. Parameters ----------- reason: :class:`str` The reason the stage instance was deleted. Shows up on the audit log. Raises ------ Forbidden You do not have permissions to delete the stage instance. HTTPException Deleting the stage instance failed. """ await self._state.http.delete_stage_instance(self.channel_id, reason=reason)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/stage_instance.py
stage_instance.py
from __future__ import annotations import time import random from typing import Callable, Generic, Literal, TypeVar, overload, Union T = TypeVar('T', bool, Literal[True], Literal[False]) __all__ = ( 'ExponentialBackoff', ) class ExponentialBackoff(Generic[T]): """An implementation of the exponential backoff algorithm Provides a convenient interface to implement an exponential backoff for reconnecting or retrying transmissions in a distributed network. Once instantiated, the delay method will return the next interval to wait for when retrying a connection or transmission. The maximum delay increases exponentially with each retry up to a maximum of 2^10 * base, and is reset if no more attempts are needed in a period of 2^11 * base seconds. Parameters ---------- base: :class:`int` The base delay in seconds. The first retry-delay will be up to this many seconds. integral: :class:`bool` Set to ``True`` if whole periods of base is desirable, otherwise any number in between may be returned. """ def __init__(self, base: int = 1, *, integral: T = False): self._base: int = base self._exp: int = 0 self._max: int = 10 self._reset_time: int = base * 2 ** 11 self._last_invocation: float = time.monotonic() # Use our own random instance to avoid messing with global one rand = random.Random() rand.seed() self._randfunc: Callable[..., Union[int, float]] = rand.randrange if integral else rand.uniform # type: ignore @overload def delay(self: ExponentialBackoff[Literal[False]]) -> float: ... @overload def delay(self: ExponentialBackoff[Literal[True]]) -> int: ... @overload def delay(self: ExponentialBackoff[bool]) -> Union[int, float]: ... def delay(self) -> Union[int, float]: """Compute the next delay Returns the next delay to wait according to the exponential backoff algorithm. This is a value between 0 and base * 2^exp where exponent starts off at 1 and is incremented at every invocation of this method up to a maximum of 10. If a period of more than base * 2^11 has passed since the last retry, the exponent is reset to 1. """ invocation = time.monotonic() interval = invocation - self._last_invocation self._last_invocation = invocation if interval > self._reset_time: self._exp = 0 self._exp = min(self._exp + 1, self._max) return self._randfunc(0, self._base * 2 ** self._exp)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/backoff.py
backoff.py
from __future__ import annotations import datetime from typing import Any, Dict, Final, List, Mapping, Protocol, TYPE_CHECKING, Type, TypeVar, Union from . import utils from .colour import Colour __all__ = ( 'Embed', ) class _EmptyEmbed: def __bool__(self) -> bool: return False def __repr__(self) -> str: return 'Embed.Empty' def __len__(self) -> int: return 0 EmptyEmbed: Final = _EmptyEmbed() class EmbedProxy: def __init__(self, layer: Dict[str, Any]): self.__dict__.update(layer) def __len__(self) -> int: return len(self.__dict__) def __repr__(self) -> str: inner = ', '.join((f'{k}={v!r}' for k, v in self.__dict__.items() if not k.startswith('_'))) return f'EmbedProxy({inner})' def __getattr__(self, attr: str) -> _EmptyEmbed: return EmptyEmbed E = TypeVar('E', bound='Embed') if TYPE_CHECKING: from discord.types.embed import Embed as EmbedData, EmbedType T = TypeVar('T') MaybeEmpty = Union[T, _EmptyEmbed] class _EmbedFooterProxy(Protocol): text: MaybeEmpty[str] icon_url: MaybeEmpty[str] class _EmbedFieldProxy(Protocol): name: MaybeEmpty[str] value: MaybeEmpty[str] inline: bool class _EmbedMediaProxy(Protocol): url: MaybeEmpty[str] proxy_url: MaybeEmpty[str] height: MaybeEmpty[int] width: MaybeEmpty[int] class _EmbedVideoProxy(Protocol): url: MaybeEmpty[str] height: MaybeEmpty[int] width: MaybeEmpty[int] class _EmbedProviderProxy(Protocol): name: MaybeEmpty[str] url: MaybeEmpty[str] class _EmbedAuthorProxy(Protocol): name: MaybeEmpty[str] url: MaybeEmpty[str] icon_url: MaybeEmpty[str] proxy_icon_url: MaybeEmpty[str] class Embed: """Represents a Discord embed. .. container:: operations .. describe:: len(x) Returns the total size of the embed. Useful for checking if it's within the 6000 character limit. .. describe:: bool(b) Returns whether the embed has any data set. .. versionadded:: 2.0 Certain properties return an ``EmbedProxy``, a type that acts similar to a regular :class:`dict` except using dotted access, e.g. ``embed.author.icon_url``. If the attribute is invalid or empty, then a special sentinel value is returned, :attr:`Embed.Empty`. For ease of use, all parameters that expect a :class:`str` are implicitly casted to :class:`str` for you. Attributes ----------- title: :class:`str` The title of the embed. This can be set during initialisation. type: :class:`str` The type of embed. Usually "rich". This can be set during initialisation. Possible strings for embed types can be found on discord's `api docs <https://discord.com/developers/docs/resources/channel#embed-object-embed-types>`_ description: :class:`str` The description of the embed. This can be set during initialisation. url: :class:`str` The URL of the embed. This can be set during initialisation. timestamp: :class:`datetime.datetime` The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone. colour: Union[:class:`Colour`, :class:`int`] The colour code of the embed. Aliased to ``color`` as well. This can be set during initialisation. Empty A special sentinel value used by ``EmbedProxy`` and this class to denote that the value or attribute is empty. """ __slots__ = ( 'title', 'url', 'type', '_timestamp', '_colour', '_footer', '_image', '_thumbnail', '_video', '_provider', '_author', '_fields', 'description', ) Empty: Final = EmptyEmbed def __init__( self, *, colour: Union[int, Colour, _EmptyEmbed] = EmptyEmbed, color: Union[int, Colour, _EmptyEmbed] = EmptyEmbed, title: MaybeEmpty[Any] = EmptyEmbed, type: EmbedType = 'rich', url: MaybeEmpty[Any] = EmptyEmbed, description: MaybeEmpty[Any] = EmptyEmbed, timestamp: datetime.datetime = None, ): self.colour = colour if colour is not EmptyEmbed else color self.title = title self.type = type self.url = url self.description = description if self.title is not EmptyEmbed: self.title = str(self.title) if self.description is not EmptyEmbed: self.description = str(self.description) if self.url is not EmptyEmbed: self.url = str(self.url) if timestamp: self.timestamp = timestamp @classmethod def from_dict(cls: Type[E], data: Mapping[str, Any]) -> E: """Converts a :class:`dict` to a :class:`Embed` provided it is in the format that Discord expects it to be in. You can find out about this format in the `official Discord documentation`__. .. _DiscordDocs: https://discord.com/developers/docs/resources/channel#embed-object __ DiscordDocs_ Parameters ----------- data: :class:`dict` The dictionary to convert into an embed. """ # we are bypassing __init__ here since it doesn't apply here self: E = cls.__new__(cls) # fill in the basic fields self.title = data.get('title', EmptyEmbed) self.type = data.get('type', EmptyEmbed) self.description = data.get('description', EmptyEmbed) self.url = data.get('url', EmptyEmbed) if self.title is not EmptyEmbed: self.title = str(self.title) if self.description is not EmptyEmbed: self.description = str(self.description) if self.url is not EmptyEmbed: self.url = str(self.url) # try to fill in the more rich fields try: self._colour = Colour(value=data['color']) except KeyError: pass try: self._timestamp = utils.parse_time(data['timestamp']) except KeyError: pass for attr in ('thumbnail', 'video', 'provider', 'author', 'fields', 'image', 'footer'): try: value = data[attr] except KeyError: continue else: setattr(self, '_' + attr, value) return self def copy(self: E) -> E: """Returns a shallow copy of the embed.""" return self.__class__.from_dict(self.to_dict()) def __len__(self) -> int: total = len(self.title) + len(self.description) for field in getattr(self, '_fields', []): total += len(field['name']) + len(field['value']) try: footer_text = self._footer['text'] except (AttributeError, KeyError): pass else: total += len(footer_text) try: author = self._author except AttributeError: pass else: total += len(author['name']) return total def __bool__(self) -> bool: return any( ( self.title, self.url, self.description, self.colour, self.fields, self.timestamp, self.author, self.thumbnail, self.footer, self.image, self.provider, self.video, ) ) @property def colour(self) -> MaybeEmpty[Colour]: return getattr(self, '_colour', EmptyEmbed) @colour.setter def colour(self, value: Union[int, Colour, _EmptyEmbed]): # type: ignore if isinstance(value, (Colour, _EmptyEmbed)): self._colour = value elif isinstance(value, int): self._colour = Colour(value=value) else: raise TypeError(f'Expected discord.Colour, int, or Embed.Empty but received {value.__class__.__name__} instead.') color = colour @property def timestamp(self) -> MaybeEmpty[datetime.datetime]: return getattr(self, '_timestamp', EmptyEmbed) @timestamp.setter def timestamp(self, value: MaybeEmpty[datetime.datetime]): if isinstance(value, datetime.datetime): if value.tzinfo is None: value = value.astimezone() self._timestamp = value elif isinstance(value, _EmptyEmbed): self._timestamp = value else: raise TypeError(f"Expected datetime.datetime or Embed.Empty received {value.__class__.__name__} instead") @property def footer(self) -> _EmbedFooterProxy: """Returns an ``EmbedProxy`` denoting the footer contents. See :meth:`set_footer` for possible values you can access. If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_footer', {})) # type: ignore def set_footer(self: E, *, text: MaybeEmpty[Any] = EmptyEmbed, icon_url: MaybeEmpty[Any] = EmptyEmbed) -> E: """Sets the footer for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- text: :class:`str` The footer text. icon_url: :class:`str` The URL of the footer icon. Only HTTP(S) is supported. """ self._footer = {} if text is not EmptyEmbed: self._footer['text'] = str(text) if icon_url is not EmptyEmbed: self._footer['icon_url'] = str(icon_url) return self def remove_footer(self: E) -> E: """Clears embed's footer information. This function returns the class instance to allow for fluent-style chaining. .. versionadded:: 2.0 """ try: del self._footer except AttributeError: pass return self @property def image(self) -> _EmbedMediaProxy: """Returns an ``EmbedProxy`` denoting the image contents. Possible attributes you can access are: - ``url`` - ``proxy_url`` - ``width`` - ``height`` If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_image', {})) # type: ignore def set_image(self: E, *, url: MaybeEmpty[Any]) -> E: """Sets the image for the embed content. This function returns the class instance to allow for fluent-style chaining. .. versionchanged:: 1.4 Passing :attr:`Empty` removes the image. Parameters ----------- url: :class:`str` The source URL for the image. Only HTTP(S) is supported. """ if url is EmptyEmbed: try: del self._image except AttributeError: pass else: self._image = { 'url': str(url), } return self @property def thumbnail(self) -> _EmbedMediaProxy: """Returns an ``EmbedProxy`` denoting the thumbnail contents. Possible attributes you can access are: - ``url`` - ``proxy_url`` - ``width`` - ``height`` If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_thumbnail', {})) # type: ignore def set_thumbnail(self: E, *, url: MaybeEmpty[Any]) -> E: """Sets the thumbnail for the embed content. This function returns the class instance to allow for fluent-style chaining. .. versionchanged:: 1.4 Passing :attr:`Empty` removes the thumbnail. Parameters ----------- url: :class:`str` The source URL for the thumbnail. Only HTTP(S) is supported. """ if url is EmptyEmbed: try: del self._thumbnail except AttributeError: pass else: self._thumbnail = { 'url': str(url), } return self @property def video(self) -> _EmbedVideoProxy: """Returns an ``EmbedProxy`` denoting the video contents. Possible attributes include: - ``url`` for the video URL. - ``height`` for the video height. - ``width`` for the video width. If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_video', {})) # type: ignore @property def provider(self) -> _EmbedProviderProxy: """Returns an ``EmbedProxy`` denoting the provider contents. The only attributes that might be accessed are ``name`` and ``url``. If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_provider', {})) # type: ignore @property def author(self) -> _EmbedAuthorProxy: """Returns an ``EmbedProxy`` denoting the author contents. See :meth:`set_author` for possible values you can access. If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_author', {})) # type: ignore def set_author(self: E, *, name: Any, url: MaybeEmpty[Any] = EmptyEmbed, icon_url: MaybeEmpty[Any] = EmptyEmbed) -> E: """Sets the author for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: :class:`str` The name of the author. url: :class:`str` The URL for the author. icon_url: :class:`str` The URL of the author icon. Only HTTP(S) is supported. """ self._author = { 'name': str(name), } if url is not EmptyEmbed: self._author['url'] = str(url) if icon_url is not EmptyEmbed: self._author['icon_url'] = str(icon_url) return self def remove_author(self: E) -> E: """Clears embed's author information. This function returns the class instance to allow for fluent-style chaining. .. versionadded:: 1.4 """ try: del self._author except AttributeError: pass return self @property def fields(self) -> List[_EmbedFieldProxy]: """List[Union[``EmbedProxy``, :attr:`Empty`]]: Returns a :class:`list` of ``EmbedProxy`` denoting the field contents. See :meth:`add_field` for possible values you can access. If the attribute has no value then :attr:`Empty` is returned. """ return [EmbedProxy(d) for d in getattr(self, '_fields', [])] # type: ignore def add_field(self: E, *, name: Any, value: Any, inline: bool = True) -> E: """Adds a field to the embed object. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: :class:`str` The name of the field. value: :class:`str` The value of the field. inline: :class:`bool` Whether the field should be displayed inline. """ field = { 'inline': inline, 'name': str(name), 'value': str(value), } try: self._fields.append(field) except AttributeError: self._fields = [field] return self def insert_field_at(self: E, index: int, *, name: Any, value: Any, inline: bool = True) -> E: """Inserts a field before a specified index to the embed. This function returns the class instance to allow for fluent-style chaining. .. versionadded:: 1.2 Parameters ----------- index: :class:`int` The index of where to insert the field. name: :class:`str` The name of the field. value: :class:`str` The value of the field. inline: :class:`bool` Whether the field should be displayed inline. """ field = { 'inline': inline, 'name': str(name), 'value': str(value), } try: self._fields.insert(index, field) except AttributeError: self._fields = [field] return self def clear_fields(self) -> None: """Removes all fields from this embed.""" try: self._fields.clear() except AttributeError: self._fields = [] def remove_field(self, index: int) -> None: """Removes a field at a specified index. If the index is invalid or out of bounds then the error is silently swallowed. .. note:: When deleting a field by index, the index of the other fields shift to fill the gap just like a regular list. Parameters ----------- index: :class:`int` The index of the field to remove. """ try: del self._fields[index] except (AttributeError, IndexError): pass def set_field_at(self: E, index: int, *, name: Any, value: Any, inline: bool = True) -> E: """Modifies a field to the embed object. The index must point to a valid pre-existing field. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- index: :class:`int` The index of the field to modify. name: :class:`str` The name of the field. value: :class:`str` The value of the field. inline: :class:`bool` Whether the field should be displayed inline. Raises ------- IndexError An invalid index was provided. """ try: field = self._fields[index] except (TypeError, IndexError, AttributeError): raise IndexError('field index out of range') field['name'] = str(name) field['value'] = str(value) field['inline'] = inline return self def to_dict(self) -> EmbedData: """Converts this embed object into a dict.""" # add in the raw data into the dict # fmt: off result = { key[1:]: getattr(self, key) for key in self.__slots__ if key[0] == '_' and hasattr(self, key) } # fmt: on # deal with basic convenience wrappers try: colour = result.pop('colour') except KeyError: pass else: if colour: result['color'] = colour.value try: timestamp = result.pop('timestamp') except KeyError: pass else: if timestamp: if timestamp.tzinfo: result['timestamp'] = timestamp.astimezone(tz=datetime.timezone.utc).isoformat() else: result['timestamp'] = timestamp.replace(tzinfo=datetime.timezone.utc).isoformat() # add in the non raw attribute ones if self.type: result['type'] = self.type if self.description: result['description'] = self.description if self.url: result['url'] = self.url if self.title: result['title'] = self.title return result # type: ignore
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/embeds.py
embeds.py
from __future__ import annotations 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 .colour import Colour from .invite import Invite from .mixins import Hashable from .object import Object from .permissions import PermissionOverwrite, Permissions __all__ = ( 'AuditLogDiff', 'AuditLogChanges', 'AuditLogEntry', ) if TYPE_CHECKING: import datetime from . import abc from .emoji import Emoji from .guild import Guild from .member import Member from .role import Role from .types.audit_log import ( AuditLogChange as AuditLogChangePayload, AuditLogEntry as AuditLogEntryPayload, ) from .types.channel import PermissionOverwrite as PermissionOverwritePayload from .types.role import Role as RolePayload from .types.snowflake import Snowflake from .user import User from .stage_instance import StageInstance from .sticker import GuildSticker from .threads import Thread def _transform_permissions(entry: AuditLogEntry, data: str) -> Permissions: return Permissions(int(data)) def _transform_color(entry: AuditLogEntry, data: int) -> Colour: return Colour(data) def _transform_snowflake(entry: AuditLogEntry, data: Snowflake) -> int: return int(data) 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) 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)) def _transform_guild_id(entry: AuditLogEntry, data: Optional[Snowflake]) -> Optional[Guild]: if data is None: return None return entry._state._get_guild(data) 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 ow_type == '0': target = entry.guild.get_role(ow_id) elif ow_type == '1': target = entry._get_member(ow_id) if target is None: target = Object(id=ow_id) overwrites.append((target, ow)) return overwrites 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) 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 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 T = TypeVar('T', bound=enums.Enum) def _enum_transformer(enum: Type[T]) -> Callable[[AuditLogEntry, int], T]: def _transform(entry: AuditLogEntry, data: int) -> T: return enums.try_enum(enum, data) return _transform def _transform_type(entry: AuditLogEntry, data: Union[int]) -> Union[enums.ChannelType, enums.StickerType]: if entry.action.name.startswith('sticker_'): return enums.try_enum(enums.StickerType, data) else: return enums.try_enum(enums.ChannelType, data) class AuditLogDiff: def __len__(self) -> int: return len(self.__dict__) def __iter__(self) -> Generator[Tuple[str, Any], None, None]: yield from self.__dict__.items() def __repr__(self) -> str: values = ' '.join('%s=%r' % item for item in self.__dict__.items()) return f'<AuditLogDiff {values}>' if TYPE_CHECKING: def __getattr__(self, item: str) -> Any: ... def __setattr__(self, key: str, value: Any) -> Any: ... Transformer = Callable[["AuditLogEntry", Any], Any] class AuditLogChanges: # fmt: off TRANSFORMERS: ClassVar[Dict[str, Tuple[Optional[str], Optional[Transformer]]]] = { 'verification_level': (None, _enum_transformer(enums.VerificationLevel)), 'explicit_content_filter': (None, _enum_transformer(enums.ContentFilter)), 'allow': (None, _transform_permissions), 'deny': (None, _transform_permissions), 'permissions': (None, _transform_permissions), 'id': (None, _transform_snowflake), 'color': ('colour', _transform_color), 'owner_id': ('owner', _transform_member_id), 'inviter_id': ('inviter', _transform_member_id), 'channel_id': ('channel', _transform_channel), 'afk_channel_id': ('afk_channel', _transform_channel), 'system_channel_id': ('system_channel', _transform_channel), 'widget_channel_id': ('widget_channel', _transform_channel), 'rules_channel_id': ('rules_channel', _transform_channel), 'public_updates_channel_id': ('public_updates_channel', _transform_channel), 'permission_overwrites': ('overwrites', _transform_overwrites), 'splash_hash': ('splash', _guild_hash_transformer('splashes')), 'banner_hash': ('banner', _guild_hash_transformer('banners')), 'discovery_splash_hash': ('discovery_splash', _guild_hash_transformer('discovery-splashes')), 'icon_hash': ('icon', _transform_icon), 'avatar_hash': ('avatar', _transform_avatar), 'rate_limit_per_user': ('slowmode_delay', None), 'guild_id': ('guild', _transform_guild_id), 'tags': ('emoji', None), 'default_message_notifications': ('default_notifications', _enum_transformer(enums.NotificationLevel)), 'region': (None, _enum_transformer(enums.VoiceRegion)), 'rtc_region': (None, _enum_transformer(enums.VoiceRegion)), 'video_quality_mode': (None, _enum_transformer(enums.VideoQualityMode)), 'privacy_level': (None, _enum_transformer(enums.StagePrivacyLevel)), 'format_type': (None, _enum_transformer(enums.StickerFormatType)), 'type': (None, _transform_type), } # fmt: on def __init__(self, entry: AuditLogEntry, data: List[AuditLogChangePayload]): self.before = AuditLogDiff() self.after = AuditLogDiff() for elem in data: attr = elem['key'] # special cases for role add/remove if attr == '$add': self._handle_role(self.before, self.after, entry, elem['new_value']) # type: ignore continue elif attr == '$remove': self._handle_role(self.after, self.before, entry, elem['new_value']) # type: ignore continue try: key, transformer = self.TRANSFORMERS[attr] except (ValueError, KeyError): transformer = None else: if key: attr = key transformer: Optional[Transformer] try: before = elem['old_value'] except KeyError: before = None else: if transformer: before = transformer(entry, before) setattr(self.before, attr, before) try: after = elem['new_value'] except KeyError: after = None else: if transformer: after = transformer(entry, after) setattr(self.after, attr, after) # add an alias if hasattr(self.after, 'colour'): self.after.color = self.after.colour self.before.color = self.before.colour if hasattr(self.after, 'expire_behavior'): self.after.expire_behaviour = self.after.expire_behavior self.before.expire_behaviour = self.before.expire_behavior def __repr__(self) -> str: return f'<AuditLogChanges before={self.before!r} after={self.after!r}>' def _handle_role(self, first: AuditLogDiff, second: AuditLogDiff, entry: AuditLogEntry, elem: List[RolePayload]) -> None: if not hasattr(first, 'roles'): setattr(first, 'roles', []) data = [] g: Guild = entry.guild # type: ignore for e in elem: role_id = int(e['id']) role = g.get_role(role_id) if role is None: role = Object(id=role_id) role.name = e['name'] # type: ignore data.append(role) setattr(second, 'roles', data) class _AuditLogProxyMemberPrune: delete_member_days: int members_removed: int class _AuditLogProxyMemberMoveOrMessageDelete: channel: abc.GuildChannel count: int class _AuditLogProxyMemberDisconnect: count: int class _AuditLogProxyPinAction: channel: abc.GuildChannel message_id: int class _AuditLogProxyStageInstanceAction: channel: abc.GuildChannel 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. """ def __init__(self, *, users: Dict[int, User], data: AuditLogEntryPayload, guild: Guild): self._state = guild._state self.guild = guild 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') 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: _AuditLogProxyMemberPrune = type( '_AuditLogProxy', (), {k: int(v) for k, v in self.extra.items()} )() elif self.action is enums.AuditLogAction.member_move or self.action is enums.AuditLogAction.message_delete: channel_id = int(self.extra['channel_id']) elems = { 'count': int(self.extra['count']), 'channel': self.guild.get_channel(channel_id) or Object(id=channel_id), } self.extra: _AuditLogProxyMemberMoveOrMessageDelete = type('_AuditLogProxy', (), elems)() elif self.action is enums.AuditLogAction.member_disconnect: # The member disconnect action has a dict with some information elems = { 'count': int(self.extra['count']), } self.extra: _AuditLogProxyMemberDisconnect = type('_AuditLogProxy', (), elems)() elif self.action.name.endswith('pin'): # the pin actions have a dict with some information channel_id = int(self.extra['channel_id']) elems = { 'channel': self.guild.get_channel(channel_id) or Object(id=channel_id), 'message_id': int(self.extra['message_id']), } self.extra: _AuditLogProxyPinAction = type('_AuditLogProxy', (), elems)() 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 = role 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)} self.extra: _AuditLogProxyStageInstanceAction = type('_AuditLogProxy', (), elems)() # fmt: off self.extra: Union[ _AuditLogProxyMemberPrune, _AuditLogProxyMemberMoveOrMessageDelete, _AuditLogProxyMemberDisconnect, _AuditLogProxyPinAction, _AuditLogProxyStageInstanceAction, Member, User, None, Role, ] # fmt: on # 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}>' @utils.cached_property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the entry's creation time in UTC.""" return utils.snowflake_time(self.id) @utils.cached_property def target(self) -> Union[Guild, abc.GuildChannel, Member, User, Role, Invite, Emoji, StageInstance, GuildSticker, Thread, Object, None]: try: converter = getattr(self, '_convert_target_' + self.action.target_type) except AttributeError: return Object(id=self._target_id) else: return converter(self._target_id) @utils.cached_property def category(self) -> enums.AuditLogActionCategory: """Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable.""" return self.action.category @utils.cached_property def changes(self) -> AuditLogChanges: """:class:`AuditLogChanges`: The list of changes this entry has.""" obj = AuditLogChanges(self, self._changes) del self._changes return obj @utils.cached_property def before(self) -> AuditLogDiff: """:class:`AuditLogDiff`: The target's prior state.""" return self.changes.before @utils.cached_property 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 try: obj.inviter = changeset.inviter except AttributeError: pass 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)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/audit_logs.py
audit_logs.py
from __future__ import annotations from typing import Optional, TYPE_CHECKING, Union import os import io __all__ = ( 'File', ) class File: r"""A parameter object used for :meth:`abc.Messageable.send` for sending file objects. .. note:: File objects are single use and are not meant to be reused in multiple :meth:`abc.Messageable.send`\s. Attributes ----------- fp: Union[:class:`os.PathLike`, :class:`io.BufferedIOBase`] A file-like object opened in binary mode and read mode or a filename representing a file in the hard drive to open. .. note:: If the file-like object passed is opened via ``open`` then the modes 'rb' should be used. To pass binary data, consider usage of ``io.BytesIO``. filename: Optional[:class:`str`] The filename to display when uploading to Discord. If this is not given then it defaults to ``fp.name`` or if ``fp`` is a string then the ``filename`` will default to the string given. spoiler: :class:`bool` Whether the attachment is a spoiler. """ __slots__ = ('fp', 'filename', 'spoiler', '_original_pos', '_owner', '_closer') if TYPE_CHECKING: fp: io.BufferedIOBase filename: Optional[str] spoiler: bool def __init__( self, fp: Union[str, bytes, os.PathLike, io.BufferedIOBase], filename: Optional[str] = None, *, spoiler: bool = False, ): if isinstance(fp, io.IOBase): if not (fp.seekable() and fp.readable()): raise ValueError(f'File buffer {fp!r} must be seekable and readable') self.fp = fp self._original_pos = fp.tell() self._owner = False else: self.fp = open(fp, 'rb') self._original_pos = 0 self._owner = True # aiohttp only uses two methods from IOBase # read and close, since I want to control when the files # close, I need to stub it so it doesn't close unless # I tell it to self._closer = self.fp.close self.fp.close = lambda: None if filename is None: if isinstance(fp, str): _, self.filename = os.path.split(fp) else: self.filename = getattr(fp, 'name', None) else: self.filename = filename if spoiler and self.filename is not None and not self.filename.startswith('SPOILER_'): self.filename = 'SPOILER_' + self.filename self.spoiler = spoiler or (self.filename is not None and self.filename.startswith('SPOILER_')) def reset(self, *, seek: Union[int, bool] = True) -> None: # The `seek` parameter is needed because # the retry-loop is iterated over multiple times # starting from 0, as an implementation quirk # the resetting must be done at the beginning # before a request is done, since the first index # is 0, and thus false, then this prevents an # unnecessary seek since it's the first request # done. if seek: self.fp.seek(self._original_pos) def close(self) -> None: self.fp.close = self._closer if self._owner: self._closer()
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/file.py
file.py
from __future__ import annotations from typing import Any, ClassVar, Dict, List, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Union from .enums import try_enum, ComponentType, ButtonStyle from .utils import get_slots, MISSING from .partial_emoji import PartialEmoji, _EmojiTag if TYPE_CHECKING: from .types.components import ( Component as ComponentPayload, ButtonComponent as ButtonComponentPayload, SelectMenu as SelectMenuPayload, SelectOption as SelectOptionPayload, ActionRow as ActionRowPayload, ) from .emoji import Emoji __all__ = ( 'Component', 'ActionRow', 'Button', 'SelectMenu', 'SelectOption', ) C = TypeVar('C', bound='Component') class Component: """Represents a Discord Bot UI Kit Component. Currently, the only components supported by Discord are: - :class:`ActionRow` - :class:`Button` - :class:`SelectMenu` This class is abstract and cannot be instantiated. .. versionadded:: 2.0 Attributes ------------ type: :class:`ComponentType` The type of component. """ __slots__: Tuple[str, ...] = ('type',) __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}>' @classmethod def _raw_construct(cls: Type[C], **kwargs) -> C: self: C = 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) -> Dict[str, Any]: 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, ...] = ('children',) __repr_info__: ClassVar[Tuple[str, ...]] = __slots__ def __init__(self, data: ComponentPayload): 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': int(self.type), 'components': [child.to_dict() for child in self.children], } # type: ignore 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:`discord.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, ...] = ( 'style', 'custom_id', 'url', 'disabled', 'label', 'emoji', ) __repr_info__: ClassVar[Tuple[str, ...]] = __slots__ def __init__(self, data: ButtonComponentPayload): 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 class SelectMenu(Component): """Represents a select menu from the Discord Bot UI Kit. A select menu is functionally the same as a dropdown, however on mobile it renders a bit differently. .. note:: The user constructible and usable type to create a select menu is :class:`discord.ui.Select` not this one. .. versionadded:: 2.0 Attributes ------------ custom_id: Optional[:class:`str`] The ID of the select menu that gets received during an interaction. 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. """ __slots__: Tuple[str, ...] = ( 'custom_id', 'placeholder', 'min_values', 'max_values', 'options', 'disabled', ) __repr_info__: ClassVar[Tuple[str, ...]] = __slots__ def __init__(self, data: SelectMenuPayload): self.type = ComponentType.select self.custom_id: str = data['custom_id'] self.placeholder: Optional[str] = data.get('placeholder') self.min_values: int = data.get('min_values', 1) self.max_values: int = data.get('max_values', 1) self.options: List[SelectOption] = [SelectOption.from_dict(option) for option in data.get('options', [])] self.disabled: bool = data.get('disabled', False) def to_dict(self) -> SelectMenuPayload: payload: SelectMenuPayload = { 'type': self.type.value, 'custom_id': self.custom_id, 'min_values': self.min_values, 'max_values': self.max_values, 'options': [op.to_dict() for op in self.options], 'disabled': self.disabled, } if self.placeholder: payload['placeholder'] = self.placeholder return payload 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 = label self.value = label if value is MISSING else value self.description = 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 = emoji self.default = 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: if self.emoji: base = f'{self.emoji} {self.label}' else: base = self.label if self.description: return f'{base}\n{self.description}' return base @classmethod 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 def _component_factory(data: ComponentPayload) -> Component: component_type = data['type'] if component_type == 1: return ActionRow(data) elif component_type == 2: return Button(data) # type: ignore elif component_type == 3: return SelectMenu(data) # type: ignore else: as_enum = try_enum(ComponentType, component_type) return Component._raw_construct(type=as_enum)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/components.py
components.py
from __future__ import annotations from typing import List, Optional, Type, TypeVar, Union, TYPE_CHECKING from .asset import Asset from .utils import parse_time, snowflake_time, _get_as_snowflake from .object import Object from .mixins import Hashable from .enums import ChannelType, VerificationLevel, InviteTarget, try_enum from .appinfo import PartialAppInfo __all__ = ( 'PartialInviteChannel', 'PartialInviteGuild', 'Invite', ) if TYPE_CHECKING: from .types.invite import ( Invite as InvitePayload, InviteGuild as InviteGuildPayload, GatewayInvite as GatewayInvitePayload, ) from .types.channel import ( PartialChannel as InviteChannelPayload, ) from .state import ConnectionState from .guild import Guild from .abc import GuildChannel from .user import User InviteGuildType = Union[Guild, 'PartialInviteGuild', Object] InviteChannelType = Union[GuildChannel, 'PartialInviteChannel', Object] import datetime class PartialInviteChannel: """Represents a "partial" invite channel. This model will be given when the user is not part of the guild the :class:`Invite` resolves to. .. container:: operations .. describe:: x == y Checks if two partial channels are the same. .. describe:: x != y Checks if two partial channels are not the same. .. describe:: hash(x) Return the partial channel's hash. .. describe:: str(x) Returns the partial channel's name. Attributes ----------- name: :class:`str` The partial channel's name. id: :class:`int` The partial channel's ID. type: :class:`ChannelType` The partial channel's type. """ __slots__ = ('id', 'name', 'type') def __init__(self, data: InviteChannelPayload): self.id: int = int(data['id']) self.name: str = data['name'] self.type: ChannelType = try_enum(ChannelType, data['type']) def __str__(self) -> str: return self.name def __repr__(self) -> str: return f'<PartialInviteChannel id={self.id} name={self.name} type={self.type!r}>' @property def mention(self) -> str: """:class:`str`: The string that allows you to mention the channel.""" return f'<#{self.id}>' @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" return snowflake_time(self.id) class PartialInviteGuild: """Represents a "partial" invite guild. This model will be given when the user is not part of the guild the :class:`Invite` resolves to. .. container:: operations .. describe:: x == y Checks if two partial guilds are the same. .. describe:: x != y Checks if two partial guilds are not the same. .. describe:: hash(x) Return the partial guild's hash. .. describe:: str(x) Returns the partial guild's name. Attributes ----------- name: :class:`str` The partial guild's name. id: :class:`int` The partial guild's ID. verification_level: :class:`VerificationLevel` The partial guild's verification level. features: List[:class:`str`] A list of features the guild has. See :attr:`Guild.features` for more information. description: Optional[:class:`str`] The partial guild's description. """ __slots__ = ('_state', 'features', '_icon', '_banner', 'id', 'name', '_splash', 'verification_level', 'description') def __init__(self, state: ConnectionState, data: InviteGuildPayload, id: int): self._state: ConnectionState = state self.id: int = id self.name: str = data['name'] self.features: List[str] = data.get('features', []) self._icon: Optional[str] = data.get('icon') self._banner: Optional[str] = data.get('banner') self._splash: Optional[str] = data.get('splash') self.verification_level: VerificationLevel = try_enum(VerificationLevel, data.get('verification_level')) self.description: Optional[str] = data.get('description') def __str__(self) -> str: return self.name def __repr__(self) -> str: return ( f'<{self.__class__.__name__} id={self.id} name={self.name!r} features={self.features} ' f'description={self.description!r}>' ) @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the guild's creation time in UTC.""" return snowflake_time(self.id) @property 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) @property 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') @property 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') I = TypeVar('I', bound='Invite') class Invite(Hashable): r"""Represents a Discord :class:`Guild` or :class:`abc.GuildChannel` invite. Depending on the way this object was created, some of the attributes can have a value of ``None``. .. container:: operations .. describe:: x == y Checks if two invites are equal. .. describe:: x != y Checks if two invites are not equal. .. describe:: hash(x) Returns the invite hash. .. describe:: str(x) Returns the invite URL. The following table illustrates what methods will obtain the attributes: +------------------------------------+------------------------------------------------------------+ | Attribute | Method | +====================================+============================================================+ | :attr:`max_age` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+------------------------------------------------------------+ | :attr:`max_uses` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+------------------------------------------------------------+ | :attr:`created_at` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+------------------------------------------------------------+ | :attr:`temporary` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+------------------------------------------------------------+ | :attr:`uses` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+------------------------------------------------------------+ | :attr:`approximate_member_count` | :meth:`Client.fetch_invite` with `with_counts` enabled | +------------------------------------+------------------------------------------------------------+ | :attr:`approximate_presence_count` | :meth:`Client.fetch_invite` with `with_counts` enabled | +------------------------------------+------------------------------------------------------------+ | :attr:`expires_at` | :meth:`Client.fetch_invite` with `with_expiration` enabled | +------------------------------------+------------------------------------------------------------+ If it's not in the table above then it is available by all methods. Attributes ----------- max_age: :class:`int` How long before the invite expires in seconds. A value of ``0`` indicates that it doesn't expire. code: :class:`str` The URL fragment used for the invite. guild: Optional[Union[:class:`Guild`, :class:`Object`, :class:`PartialInviteGuild`]] The guild the invite is for. Can be ``None`` if it's from a group direct message. revoked: :class:`bool` Indicates if the invite has been revoked. created_at: :class:`datetime.datetime` An aware UTC datetime object denoting the time the invite was created. temporary: :class:`bool` Indicates that the invite grants temporary membership. If ``True``, members who joined via this invite will be kicked upon disconnect. uses: :class:`int` How many times the invite has been used. max_uses: :class:`int` How many times the invite can be used. A value of ``0`` indicates that it has unlimited uses. inviter: Optional[:class:`User`] The user who created the invite. approximate_member_count: Optional[:class:`int`] The approximate number of members in the guild. 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. expires_at: Optional[:class:`datetime.datetime`] The expiration date of the invite. If the value is ``None`` when received through `Client.fetch_invite` with `with_expiration` enabled, the invite will never expire. .. versionadded:: 2.0 channel: Union[:class:`abc.GuildChannel`, :class:`Object`, :class:`PartialInviteChannel`] The channel the invite is for. target_type: :class:`InviteTarget` The type of target for the voice channel invite. .. versionadded:: 2.0 target_user: Optional[:class:`User`] The user whose stream to display for this invite, if any. .. versionadded:: 2.0 target_application: Optional[:class:`PartialAppInfo`] The embedded application the invite targets, if any. .. versionadded:: 2.0 """ __slots__ = ( 'max_age', 'code', 'guild', 'revoked', 'created_at', 'uses', 'temporary', 'max_uses', 'inviter', 'channel', 'target_user', 'target_type', '_state', 'approximate_member_count', 'approximate_presence_count', 'target_application', 'expires_at', ) BASE = 'https://discord.gg' def __init__( self, *, state: ConnectionState, data: InvitePayload, guild: Optional[Union[PartialInviteGuild, Guild]] = None, channel: Optional[Union[PartialInviteChannel, GuildChannel]] = None, ): self._state: ConnectionState = state self.max_age: Optional[int] = data.get('max_age') self.code: str = data['code'] self.guild: Optional[InviteGuildType] = self._resolve_guild(data.get('guild'), guild) self.revoked: Optional[bool] = data.get('revoked') self.created_at: Optional[datetime.datetime] = parse_time(data.get('created_at')) self.temporary: Optional[bool] = data.get('temporary') self.uses: Optional[int] = data.get('uses') self.max_uses: Optional[int] = data.get('max_uses') self.approximate_presence_count: Optional[int] = data.get('approximate_presence_count') self.approximate_member_count: Optional[int] = data.get('approximate_member_count') expires_at = data.get('expires_at', None) self.expires_at: Optional[datetime.datetime] = parse_time(expires_at) if expires_at else None inviter_data = data.get('inviter') self.inviter: Optional[User] = None if inviter_data is None else self._state.create_user(inviter_data) self.channel: Optional[InviteChannelType] = self._resolve_channel(data.get('channel'), channel) target_user_data = data.get('target_user') self.target_user: Optional[User] = None if target_user_data is None else self._state.create_user(target_user_data) self.target_type: InviteTarget = try_enum(InviteTarget, data.get("target_type", 0)) application = data.get('target_application') self.target_application: Optional[PartialAppInfo] = ( PartialAppInfo(data=application, state=state) if application else None ) @classmethod def from_incomplete(cls: Type[I], *, state: ConnectionState, data: InvitePayload) -> I: guild: Optional[Union[Guild, PartialInviteGuild]] try: guild_data = data['guild'] except KeyError: # If we're here, then this is a group DM guild = None else: guild_id = int(guild_data['id']) guild = state._get_guild(guild_id) if guild is None: # If it's not cached, then it has to be a partial guild guild = PartialInviteGuild(state, guild_data, guild_id) # As far as I know, invites always need a channel # So this should never raise. channel: Union[PartialInviteChannel, GuildChannel] = PartialInviteChannel(data['channel']) if guild is not None and not isinstance(guild, PartialInviteGuild): # Upgrade the partial data if applicable channel = guild.get_channel(channel.id) or channel return cls(state=state, data=data, guild=guild, channel=channel) @classmethod def from_gateway(cls: Type[I], *, state: ConnectionState, data: GatewayInvitePayload) -> I: guild_id: Optional[int] = _get_as_snowflake(data, 'guild_id') guild: Optional[Union[Guild, Object]] = state._get_guild(guild_id) channel_id = int(data['channel_id']) if guild is not None: channel = guild.get_channel(channel_id) or Object(id=channel_id) # type: ignore else: guild = Object(id=guild_id) if guild_id is not None else None channel = Object(id=channel_id) return cls(state=state, data=data, guild=guild, channel=channel) # type: ignore def _resolve_guild( self, data: Optional[InviteGuildPayload], guild: Optional[Union[Guild, PartialInviteGuild]] = None, ) -> Optional[InviteGuildType]: if guild is not None: return guild if data is None: return None guild_id = int(data['id']) return PartialInviteGuild(self._state, data, guild_id) def _resolve_channel( self, data: Optional[InviteChannelPayload], channel: Optional[Union[PartialInviteChannel, GuildChannel]] = None, ) -> Optional[InviteChannelType]: if channel is not None: return channel if data is None: return None return PartialInviteChannel(data) def __str__(self) -> str: return self.url def __repr__(self) -> str: return ( f'<Invite code={self.code!r} guild={self.guild!r} ' f'online={self.approximate_presence_count} ' f'members={self.approximate_member_count}>' ) def __hash__(self) -> int: return hash(self.code) @property def id(self) -> str: """:class:`str`: Returns the proper code portion of the invite.""" return self.code @property def url(self) -> str: """:class:`str`: A property that retrieves the invite URL.""" return self.BASE + '/' + self.code async def delete(self, *, reason: Optional[str] = None): """|coro| Revokes the instant invite. You must have the :attr:`~Permissions.manage_channels` permission to do this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this invite. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to revoke invites. NotFound The invite is invalid or expired. HTTPException Revoking the invite failed. """ await self._state.http.delete_invite(self.code, reason=reason)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/invite.py
invite.py
from __future__ import annotations from typing import Callable, Dict, Iterable, List, Optional, Union, TYPE_CHECKING import time import asyncio from .mixins import Hashable from .abc import Messageable from .enums import ChannelType, try_enum from .errors import ClientException from .utils import MISSING, parse_time, _get_as_snowflake __all__ = ( 'Thread', 'ThreadMember', ) if TYPE_CHECKING: from .types.threads import ( Thread as ThreadPayload, ThreadMember as ThreadMemberPayload, ThreadMetadata, ThreadArchiveDuration, ) from .types.snowflake import SnowflakeList from .guild import Guild from .channel import TextChannel, CategoryChannel from .member import Member from .message import Message, PartialMessage from .abc import Snowflake, SnowflakeTime from .role import Role from .permissions import Permissions from .state import ConnectionState class Thread(Messageable, Hashable): """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. """ __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', ) def __init__(self, *, guild: Guild, state: ConnectionState, data: ThreadPayload): 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): 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']) try: member = data['member'] except KeyError: self.me = None else: self.me = ThreadMember(self, member) def _unroll_metadata(self, data: ThreadMetadata): 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) def _update(self, data): try: self.name = data['name'] except KeyError: pass self.slowmode_delay = data.get('rate_limit_per_user', 0) try: self._unroll_metadata(data['thread_metadata']) except KeyError: pass @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return self._type @property def parent(self) -> Optional[TextChannel]: """Optional[:class:`TextChannel`]: The parent channel this thread belongs to.""" return self.guild.get_channel(self.parent_id) # type: ignore @property def owner(self) -> Optional[Member]: """Optional[:class:`Member`]: The member this thread belongs to.""" return self.guild.get_member(self.owner_id) @property def mention(self) -> str: """:class:`str`: The string that allows you to mention the thread.""" return f'<#{self.id}>' @property 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()) @property 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 @property 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 @property 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 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:`~discord.Member` or :class:`~discord.Role`. Since threads do not have their own permissions, they inherit them from the parent channel. This is a convenience method for calling :meth:`~discord.TextChannel.permissions_for` on the parent channel. Parameters ---------- obj: Union[:class:`~discord.Member`, :class:`~discord.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:`~discord.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 m: 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]): 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, ) -> 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``. 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 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): """|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): """|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): """|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): """|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): """|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) class ThreadMember(Hashable): """Represents a Discord thread member. .. container:: operations .. describe:: x == y Checks if two thread members are equal. .. describe:: x != y Checks if two thread members are not equal. .. describe:: hash(x) Returns the thread member's hash. .. describe:: str(x) Returns the thread member's name. .. versionadded:: 2.0 Attributes ----------- id: :class:`int` The thread member's ID. thread_id: :class:`int` The thread's ID. joined_at: :class:`datetime.datetime` The time the member joined the thread in UTC. """ __slots__ = ( 'id', 'thread_id', 'joined_at', 'flags', '_state', 'parent', ) def __init__(self, parent: Thread, data: ThreadMemberPayload): self.parent = parent self._state = parent._state self._from_data(data) def __repr__(self) -> str: return f'<ThreadMember id={self.id} thread_id={self.thread_id} joined_at={self.joined_at!r}>' def _from_data(self, data: ThreadMemberPayload): try: self.id = int(data['user_id']) except KeyError: assert self._state.self_id is not None self.id = self._state.self_id try: self.thread_id = int(data['id']) except KeyError: self.thread_id = self.parent.id self.joined_at = parse_time(data['join_timestamp']) self.flags = data['flags'] @property def thread(self) -> Thread: """:class:`Thread`: The thread this member belongs to.""" return self.parent
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/threads.py
threads.py
from __future__ import annotations import time import asyncio from typing import ( Any, Callable, Dict, Iterable, List, Mapping, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Union, overload, ) import datetime import discord.abc from .permissions import PermissionOverwrite, Permissions from .enums import ChannelType, StagePrivacyLevel, try_enum, VoiceRegion, VideoQualityMode from .mixins import Hashable from .object import Object from . import utils from .utils import MISSING from .asset import Asset from .errors import ClientException, InvalidArgument from .stage_instance import StageInstance from .threads import Thread from .iterators import ArchivedThreadIterator __all__ = ( 'TextChannel', 'VoiceChannel', 'StageChannel', 'DMChannel', 'CategoryChannel', 'StoreChannel', 'GroupChannel', 'PartialMessageable', ) if TYPE_CHECKING: from .types.threads import ThreadArchiveDuration from .role import Role from .member import Member, VoiceState from .abc import Snowflake, SnowflakeTime from .message import Message, PartialMessage from .webhook import Webhook from .state import ConnectionState from .user import ClientUser, User, BaseUser from .guild import Guild, GuildChannel as GuildChannelType from .types.channel import ( TextChannel as TextChannelPayload, VoiceChannel as VoiceChannelPayload, StageChannel as StageChannelPayload, DMChannel as DMChannelPayload, CategoryChannel as CategoryChannelPayload, StoreChannel as StoreChannelPayload, GroupDMChannel as GroupChannelPayload, ) from .types.snowflake import SnowflakeList async def _single_delete_strategy(messages: Iterable[Message]): for m in messages: await m.delete() class TextChannel(discord.abc.Messageable, discord.abc.GuildChannel, Hashable): """Represents a Discord guild text channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns the channel's name. Attributes ----------- name: :class:`str` The channel name. guild: :class:`Guild` The guild the channel belongs to. id: :class:`int` The channel ID. category_id: Optional[:class:`int`] The category channel ID this channel belongs to, if applicable. topic: Optional[:class:`str`] The channel's topic. ``None`` if it doesn't exist. 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. last_message_id: Optional[:class:`int`] The last message ID of the message sent to this channel. 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 channel. A value of `0` denotes that it is disabled. Bots and users with :attr:`~Permissions.manage_channels` or :attr:`~Permissions.manage_messages` bypass slowmode. nsfw: :class:`bool` If the channel is marked as "not safe for work". .. note:: To check if the channel or the guild of that channel are marked as NSFW, consider :meth:`is_nsfw` instead. default_auto_archive_duration: :class:`int` The default auto archive duration in minutes for threads created in this channel. .. versionadded:: 2.0 """ __slots__ = ( 'name', 'id', 'guild', 'topic', '_state', 'nsfw', 'category_id', 'position', 'slowmode_delay', '_overwrites', '_type', 'last_message_id', 'default_auto_archive_duration', ) def __init__(self, *, state: ConnectionState, guild: Guild, data: TextChannelPayload): self._state: ConnectionState = state self.id: int = int(data['id']) self._type: int = data['type'] self._update(guild, data) def __repr__(self) -> str: attrs = [ ('id', self.id), ('name', self.name), ('position', self.position), ('nsfw', self.nsfw), ('news', self.is_news()), ('category_id', self.category_id), ] joined = ' '.join('%s=%r' % t for t in attrs) return f'<{self.__class__.__name__} {joined}>' def _update(self, guild: Guild, data: TextChannelPayload) -> None: self.guild: Guild = guild self.name: str = data['name'] self.category_id: Optional[int] = utils._get_as_snowflake(data, 'parent_id') self.topic: Optional[str] = data.get('topic') self.position: int = data['position'] self.nsfw: bool = data.get('nsfw', False) # Does this need coercion into `int`? No idea yet. self.slowmode_delay: int = data.get('rate_limit_per_user', 0) self.default_auto_archive_duration: ThreadArchiveDuration = data.get('default_auto_archive_duration', 1440) self._type: int = data.get('type', self._type) self.last_message_id: Optional[int] = utils._get_as_snowflake(data, 'last_message_id') self._fill_overwrites(data) async def _get_channel(self): return self @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return try_enum(ChannelType, self._type) @property def _sorting_bucket(self) -> int: return ChannelType.text.value @utils.copy_doc(discord.abc.GuildChannel.permissions_for) def permissions_for(self, obj: Union[Member, Role], /) -> Permissions: base = super().permissions_for(obj) # text channels do not have voice related permissions denied = Permissions.voice() base.value &= ~denied.value return base @property def members(self) -> List[Member]: """List[:class:`Member`]: Returns all members that can see this channel.""" return [m for m in self.guild.members if self.permissions_for(m).read_messages] @property def threads(self) -> List[Thread]: """List[:class:`Thread`]: Returns all the threads that you can see. .. versionadded:: 2.0 """ return [thread for thread in self.guild._threads.values() if thread.parent_id == self.id] def is_nsfw(self) -> bool: """:class:`bool`: Checks if the channel is NSFW.""" return self.nsfw def is_news(self) -> bool: """:class:`bool`: Checks if the channel is a news channel.""" return self._type == ChannelType.news.value @property 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 @overload async def edit( self, *, reason: Optional[str] = ..., name: str = ..., topic: str = ..., position: int = ..., nsfw: bool = ..., sync_permissions: bool = ..., category: Optional[CategoryChannel] = ..., slowmode_delay: int = ..., default_auto_archive_duration: ThreadArchiveDuration = ..., type: ChannelType = ..., overwrites: Mapping[Union[Role, Member, Snowflake], PermissionOverwrite] = ..., ) -> Optional[TextChannel]: ... @overload async def edit(self) -> Optional[TextChannel]: ... async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionchanged:: 1.3 The ``overwrites`` keyword-only parameter was added. .. versionchanged:: 1.4 The ``type`` keyword-only parameter was added. .. versionchanged:: 2.0 Edits are no longer in-place, the newly edited channel is returned instead. Parameters ---------- name: :class:`str` The new channel name. topic: :class:`str` The new channel's topic. position: :class:`int` The new channel's position. nsfw: :class:`bool` To mark the channel as NSFW or not. sync_permissions: :class:`bool` Whether to sync permissions with the channel's new or pre-existing category. Defaults to ``False``. category: Optional[:class:`CategoryChannel`] The new category for this channel. Can be ``None`` to remove the category. slowmode_delay: :class:`int` Specifies the slowmode rate limit for user in this channel, in seconds. A value of `0` disables slowmode. The maximum value possible is `21600`. type: :class:`ChannelType` Change the type of this text channel. Currently, only conversion between :attr:`ChannelType.text` and :attr:`ChannelType.news` is supported. This is only available to guilds that contain ``NEWS`` in :attr:`Guild.features`. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. overwrites: :class:`Mapping` A :class:`Mapping` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. default_auto_archive_duration: :class:`int` The new default auto archive duration in minutes for threads created in this channel. Must be one of ``60``, ``1440``, ``4320``, or ``10080``. Raises ------ InvalidArgument If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form. Forbidden You do not have permissions to edit the channel. HTTPException Editing the channel failed. Returns -------- Optional[:class:`.TextChannel`] The newly edited text channel. If the edit was only positional then ``None`` is returned instead. """ payload = await self._edit(options, reason=reason) if payload is not None: # the payload will always be the proper channel payload return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> TextChannel: return await self._clone_impl( {'topic': self.topic, 'nsfw': self.nsfw, 'rate_limit_per_user': self.slowmode_delay}, name=name, reason=reason ) 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. 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. 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: int = 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. 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 channel.purge(limit=100, check=is_me) await channel.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 m: 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 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 webhooks(self) -> List[Webhook]: """|coro| Gets the list of webhooks from this channel. 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 channel. """ from .webhook import Webhook data = await self._state.http.channel_webhooks(self.id) return [Webhook.from_state(d, state=self._state) for d in data] async def create_webhook(self, *, name: str, avatar: Optional[bytes] = None, reason: Optional[str] = None) -> Webhook: """|coro| Creates a webhook for this channel. Requires :attr:`~.Permissions.manage_webhooks` permissions. .. versionchanged:: 1.1 Added the ``reason`` keyword-only parameter. Parameters ------------- name: :class:`str` The webhook's name. avatar: Optional[:class:`bytes`] A :term:`py:bytes-like object` representing the webhook's default avatar. This operates similarly to :meth:`~ClientUser.edit`. reason: Optional[:class:`str`] The reason for creating this webhook. Shows up in the audit logs. Raises ------- HTTPException Creating the webhook failed. Forbidden You do not have permissions to create a webhook. Returns -------- :class:`Webhook` The created webhook. """ from .webhook import Webhook if avatar is not None: avatar = utils._bytes_to_base64_data(avatar) # type: ignore data = await self._state.http.create_webhook(self.id, name=str(name), avatar=avatar, reason=reason) return Webhook.from_state(data, state=self._state) async def follow(self, *, destination: TextChannel, reason: Optional[str] = None) -> Webhook: """ Follows a channel using a webhook. Only news channels can be followed. .. note:: The webhook returned will not provide a token to do webhook actions, as Discord does not provide it. .. versionadded:: 1.3 Parameters ----------- destination: :class:`TextChannel` The channel you would like to follow from. reason: Optional[:class:`str`] The reason for following the channel. Shows up on the destination guild's audit log. .. versionadded:: 1.4 Raises ------- HTTPException Following the channel failed. Forbidden You do not have the permissions to create a webhook. Returns -------- :class:`Webhook` The created webhook. """ if not self.is_news(): raise ClientException('The channel must be a news channel.') if not isinstance(destination, TextChannel): raise InvalidArgument(f'Expected TextChannel received {destination.__class__.__name__}') from .webhook import Webhook data = await self._state.http.follow_webhook(self.id, webhook_channel_id=destination.id, reason=reason) return Webhook._as_follower(data, channel=destination, user=self._state.user) 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:: 1.6 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 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.guild.get_thread(thread_id) async def create_thread( self, *, name: str, message: Optional[Snowflake] = None, auto_archive_duration: ThreadArchiveDuration = MISSING, type: Optional[ChannelType] = None, reason: Optional[str] = None, ) -> Thread: """|coro| Creates a thread in this text channel. To create a public thread, you must have :attr:`~discord.Permissions.create_public_threads`. For a private thread, :attr:`~discord.Permissions.create_private_threads` is needed instead. .. versionadded:: 2.0 Parameters ----------- name: :class:`str` The name of the thread. message: Optional[:class:`abc.Snowflake`] A snowflake representing the message to create the thread with. If ``None`` is passed then a private thread is created. Defaults to ``None``. auto_archive_duration: :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. type: Optional[:class:`ChannelType`] The type of thread to create. If a ``message`` is passed then this parameter is ignored, as a thread created with a message is always a public thread. By default this creates a private thread if this is ``None``. reason: :class:`str` The reason for creating a new thread. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to create a thread. HTTPException Starting the thread failed. Returns -------- :class:`Thread` The created thread """ if type is None: type = ChannelType.private_thread if message is None: data = await self._state.http.start_thread_without_message( self.id, name=name, auto_archive_duration=auto_archive_duration or self.default_auto_archive_duration, type=type.value, reason=reason, ) else: data = await self._state.http.start_thread_with_message( self.id, message.id, name=name, auto_archive_duration=auto_archive_duration or self.default_auto_archive_duration, reason=reason, ) return Thread(guild=self.guild, state=self._state, data=data) def archived_threads( self, *, private: bool = False, joined: bool = False, limit: Optional[int] = 50, before: Optional[Union[Snowflake, datetime.datetime]] = None, ) -> ArchivedThreadIterator: """Returns an :class:`~discord.AsyncIterator` that iterates over all archived threads in the guild. You must have :attr:`~Permissions.read_message_history` to use this. If iterating over private threads then :attr:`~Permissions.manage_threads` is also required. .. versionadded:: 2.0 Parameters ----------- limit: Optional[:class:`bool`] The number of threads to retrieve. If ``None``, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation. before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Retrieve archived channels before the given date or ID. private: :class:`bool` Whether to retrieve private archived threads. joined: :class:`bool` Whether to retrieve private archived threads that you've joined. You cannot set ``joined`` to ``True`` and ``private`` to ``False``. Raises ------ Forbidden You do not have permissions to get archived threads. HTTPException The request to get the archived threads failed. Yields ------- :class:`Thread` The archived threads. """ return ArchivedThreadIterator(self.id, self.guild, limit=limit, joined=joined, private=private, before=before) class VocalGuildChannel(discord.abc.Connectable, discord.abc.GuildChannel, Hashable): __slots__ = ( 'name', 'id', 'guild', 'bitrate', 'user_limit', '_state', 'position', '_overwrites', 'category_id', 'rtc_region', 'video_quality_mode', ) def __init__(self, *, state: ConnectionState, guild: Guild, data: Union[VoiceChannelPayload, StageChannelPayload]): self._state: ConnectionState = state self.id: int = int(data['id']) self._update(guild, data) def _get_voice_client_key(self) -> Tuple[int, str]: return self.guild.id, 'guild_id' def _get_voice_state_pair(self) -> Tuple[int, int]: return self.guild.id, self.id def _update(self, guild: Guild, data: Union[VoiceChannelPayload, StageChannelPayload]) -> None: self.guild = guild self.name: str = data['name'] rtc = data.get('rtc_region') self.rtc_region: Optional[VoiceRegion] = try_enum(VoiceRegion, rtc) if rtc is not None else None self.video_quality_mode: VideoQualityMode = try_enum(VideoQualityMode, data.get('video_quality_mode', 1)) self.category_id: Optional[int] = utils._get_as_snowflake(data, 'parent_id') self.position: int = data['position'] self.bitrate: int = data.get('bitrate') self.user_limit: int = data.get('user_limit') self._fill_overwrites(data) @property def _sorting_bucket(self) -> int: return ChannelType.voice.value @property def members(self) -> List[Member]: """List[:class:`Member`]: Returns all members that are currently inside this voice channel.""" ret = [] for user_id, state in self.guild._voice_states.items(): if state.channel and state.channel.id == self.id: member = self.guild.get_member(user_id) if member is not None: ret.append(member) return ret @property def voice_states(self) -> Dict[int, VoiceState]: """Returns a mapping of member IDs who have voice states in this channel. .. versionadded:: 1.3 .. note:: This function is intentionally low level to replace :attr:`members` when the member cache is unavailable. Returns -------- Mapping[:class:`int`, :class:`VoiceState`] The mapping of member ID to a voice state. """ # fmt: off return { key: value for key, value in self.guild._voice_states.items() if value.channel and value.channel.id == self.id } # fmt: on @utils.copy_doc(discord.abc.GuildChannel.permissions_for) def permissions_for(self, obj: Union[Member, Role], /) -> Permissions: base = super().permissions_for(obj) # voice channels cannot be edited by people who can't connect to them # It also implicitly denies all other voice perms if not base.connect: denied = Permissions.voice() denied.update(manage_channels=True, manage_roles=True) base.value &= ~denied.value return base class VoiceChannel(VocalGuildChannel): """Represents a Discord guild voice channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns the channel's name. Attributes ----------- name: :class:`str` The channel name. guild: :class:`Guild` The guild the channel belongs to. id: :class:`int` The channel ID. category_id: Optional[:class:`int`] The category channel ID this channel belongs to, if applicable. 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 """ __slots__ = () def __repr__(self) -> str: attrs = [ ('id', self.id), ('name', self.name), ('rtc_region', self.rtc_region), ('position', self.position), ('bitrate', self.bitrate), ('video_quality_mode', self.video_quality_mode), ('user_limit', self.user_limit), ('category_id', self.category_id), ] joined = ' '.join('%s=%r' % t for t in attrs) return f'<{self.__class__.__name__} {joined}>' @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.voice @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> VoiceChannel: return await self._clone_impl({'bitrate': self.bitrate, 'user_limit': self.user_limit}, name=name, reason=reason) @overload async def edit( self, *, name: str = ..., bitrate: int = ..., user_limit: int = ..., position: int = ..., sync_permissions: int = ..., category: Optional[CategoryChannel] = ..., overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = ..., rtc_region: Optional[VoiceRegion] = ..., video_quality_mode: VideoQualityMode = ..., reason: Optional[str] = ..., ) -> Optional[VoiceChannel]: ... @overload async def edit(self) -> Optional[VoiceChannel]: ... async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionchanged:: 1.3 The ``overwrites`` keyword-only parameter was added. .. versionchanged:: 2.0 Edits are no longer in-place, the newly edited channel is returned instead. Parameters ---------- name: :class:`str` The new channel's name. bitrate: :class:`int` The new channel's bitrate. user_limit: :class:`int` The new channel's user limit. position: :class:`int` The new channel's position. sync_permissions: :class:`bool` Whether to sync permissions with the channel's new or pre-existing category. Defaults to ``False``. category: Optional[:class:`CategoryChannel`] The new category for this channel. Can be ``None`` to remove the category. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. overwrites: :class:`Mapping` A :class:`Mapping` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. rtc_region: Optional[:class:`VoiceRegion`] The new 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 Raises ------ InvalidArgument If the permission overwrite information is not in proper form. Forbidden You do not have permissions to edit the channel. HTTPException Editing the channel failed. Returns -------- Optional[:class:`.VoiceChannel`] The newly edited voice channel. If the edit was only positional then ``None`` is returned instead. """ payload = await self._edit(options, reason=reason) if payload is not None: # the payload will always be the proper channel payload return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore class StageChannel(VocalGuildChannel): """Represents a Discord guild stage channel. .. versionadded:: 1.7 .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns the channel's name. Attributes ----------- name: :class:`str` The channel name. guild: :class:`Guild` The guild the channel belongs to. id: :class:`int` The channel ID. topic: Optional[:class:`str`] The channel's topic. ``None`` if it isn't set. category_id: Optional[:class:`int`] The category channel ID this channel belongs to, if applicable. 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 stage channel. rtc_region: Optional[:class:`VoiceRegion`] The region for the stage channel's voice communication. A value of ``None`` indicates automatic voice region detection. video_quality_mode: :class:`VideoQualityMode` The camera video quality for the stage channel's participants. .. versionadded:: 2.0 """ __slots__ = ('topic',) def __repr__(self) -> str: attrs = [ ('id', self.id), ('name', self.name), ('topic', self.topic), ('rtc_region', self.rtc_region), ('position', self.position), ('bitrate', self.bitrate), ('video_quality_mode', self.video_quality_mode), ('user_limit', self.user_limit), ('category_id', self.category_id), ] joined = ' '.join('%s=%r' % t for t in attrs) return f'<{self.__class__.__name__} {joined}>' def _update(self, guild: Guild, data: StageChannelPayload) -> None: super()._update(guild, data) self.topic = data.get('topic') @property def requesting_to_speak(self) -> List[Member]: """List[:class:`Member`]: A list of members who are requesting to speak in the stage channel.""" return [member for member in self.members if member.voice and member.voice.requested_to_speak_at is not None] @property def speakers(self) -> List[Member]: """List[:class:`Member`]: A list of members who have been permitted to speak in the stage channel. .. versionadded:: 2.0 """ return [ member for member in self.members if member.voice and not member.voice.suppress and member.voice.requested_to_speak_at is None ] @property def listeners(self) -> List[Member]: """List[:class:`Member`]: A list of members who are listening in the stage channel. .. versionadded:: 2.0 """ return [member for member in self.members if member.voice and member.voice.suppress] @property def moderators(self) -> List[Member]: """List[:class:`Member`]: A list of members who are moderating the stage channel. .. versionadded:: 2.0 """ required_permissions = Permissions.stage_moderator() return [member for member in self.members if self.permissions_for(member) >= required_permissions] @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.stage_voice @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> StageChannel: return await self._clone_impl({}, name=name, reason=reason) @property def instance(self) -> Optional[StageInstance]: """Optional[:class:`StageInstance`]: The running stage instance of the stage channel. .. versionadded:: 2.0 """ return utils.get(self.guild.stage_instances, channel_id=self.id) async def create_instance( self, *, topic: str, privacy_level: StagePrivacyLevel = MISSING, reason: Optional[str] = None ) -> StageInstance: """|coro| Create a stage instance. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionadded:: 2.0 Parameters ----------- topic: :class:`str` The stage instance's topic. privacy_level: :class:`StagePrivacyLevel` The stage instance's privacy level. Defaults to :attr:`StagePrivacyLevel.guild_only`. reason: :class:`str` The reason the stage instance was created. Shows up on the audit log. Raises ------ InvalidArgument If the ``privacy_level`` parameter is not the proper type. Forbidden You do not have permissions to create a stage instance. HTTPException Creating a stage instance failed. Returns -------- :class:`StageInstance` The newly created stage instance. """ payload: Dict[str, Any] = {'channel_id': self.id, 'topic': topic} if privacy_level is not MISSING: if not isinstance(privacy_level, StagePrivacyLevel): raise InvalidArgument('privacy_level field must be of type PrivacyLevel') payload['privacy_level'] = privacy_level.value data = await self._state.http.create_stage_instance(**payload, reason=reason) return StageInstance(guild=self.guild, state=self._state, data=data) async def fetch_instance(self) -> StageInstance: """|coro| Gets the running :class:`StageInstance`. .. versionadded:: 2.0 Raises ------- :exc:`.NotFound` The stage instance or channel could not be found. :exc:`.HTTPException` Getting the stage instance failed. Returns -------- :class:`StageInstance` The stage instance. """ data = await self._state.http.get_stage_instance(self.id) return StageInstance(guild=self.guild, state=self._state, data=data) @overload async def edit( self, *, name: str = ..., topic: Optional[str] = ..., position: int = ..., sync_permissions: int = ..., category: Optional[CategoryChannel] = ..., overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = ..., rtc_region: Optional[VoiceRegion] = ..., video_quality_mode: VideoQualityMode = ..., reason: Optional[str] = ..., ) -> Optional[StageChannel]: ... @overload async def edit(self) -> Optional[StageChannel]: ... async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionchanged:: 2.0 The ``topic`` parameter must now be set via :attr:`create_instance`. .. versionchanged:: 2.0 Edits are no longer in-place, the newly edited channel is returned instead. Parameters ---------- name: :class:`str` The new channel's name. position: :class:`int` The new channel's position. sync_permissions: :class:`bool` Whether to sync permissions with the channel's new or pre-existing category. Defaults to ``False``. category: Optional[:class:`CategoryChannel`] The new category for this channel. Can be ``None`` to remove the category. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. overwrites: :class:`Mapping` A :class:`Mapping` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. rtc_region: Optional[:class:`VoiceRegion`] The new region for the stage channel's voice communication. A value of ``None`` indicates automatic voice region detection. video_quality_mode: :class:`VideoQualityMode` The camera video quality for the stage channel's participants. .. versionadded:: 2.0 Raises ------ InvalidArgument If the permission overwrite information is not in proper form. Forbidden You do not have permissions to edit the channel. HTTPException Editing the channel failed. Returns -------- Optional[:class:`.StageChannel`] The newly edited stage channel. If the edit was only positional then ``None`` is returned instead. """ payload = await self._edit(options, reason=reason) if payload is not None: # the payload will always be the proper channel payload return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore class CategoryChannel(discord.abc.GuildChannel, Hashable): """Represents a Discord channel category. These are useful to group channels to logical compartments. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the category's hash. .. describe:: str(x) Returns the category's name. Attributes ----------- name: :class:`str` The category name. guild: :class:`Guild` The guild the category belongs to. id: :class:`int` The category channel ID. position: :class:`int` The position in the category list. This is a number that starts at 0. e.g. the top category is position 0. nsfw: :class:`bool` If the channel is marked as "not safe for work". .. note:: To check if the channel or the guild of that channel are marked as NSFW, consider :meth:`is_nsfw` instead. """ __slots__ = ('name', 'id', 'guild', 'nsfw', '_state', 'position', '_overwrites', 'category_id') def __init__(self, *, state: ConnectionState, guild: Guild, data: CategoryChannelPayload): self._state: ConnectionState = state self.id: int = int(data['id']) self._update(guild, data) def __repr__(self) -> str: return f'<CategoryChannel id={self.id} name={self.name!r} position={self.position} nsfw={self.nsfw}>' def _update(self, guild: Guild, data: CategoryChannelPayload) -> None: self.guild: Guild = guild self.name: str = data['name'] self.category_id: Optional[int] = utils._get_as_snowflake(data, 'parent_id') self.nsfw: bool = data.get('nsfw', False) self.position: int = data['position'] self._fill_overwrites(data) @property def _sorting_bucket(self) -> int: return ChannelType.category.value @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.category def is_nsfw(self) -> bool: """:class:`bool`: Checks if the category is NSFW.""" return self.nsfw @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> CategoryChannel: return await self._clone_impl({'nsfw': self.nsfw}, name=name, reason=reason) @overload async def edit( self, *, name: str = ..., position: int = ..., nsfw: bool = ..., overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = ..., reason: Optional[str] = ..., ) -> Optional[CategoryChannel]: ... @overload async def edit(self) -> Optional[CategoryChannel]: ... async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionchanged:: 1.3 The ``overwrites`` keyword-only parameter was added. .. versionchanged:: 2.0 Edits are no longer in-place, the newly edited channel is returned instead. Parameters ---------- name: :class:`str` The new category's name. position: :class:`int` The new category's position. nsfw: :class:`bool` To mark the category as NSFW or not. reason: Optional[:class:`str`] The reason for editing this category. Shows up on the audit log. overwrites: :class:`Mapping` A :class:`Mapping` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. Raises ------ InvalidArgument If position is less than 0 or greater than the number of categories. Forbidden You do not have permissions to edit the category. HTTPException Editing the category failed. Returns -------- Optional[:class:`.CategoryChannel`] The newly edited category channel. If the edit was only positional then ``None`` is returned instead. """ payload = await self._edit(options, reason=reason) if payload is not None: # the payload will always be the proper channel payload return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore @utils.copy_doc(discord.abc.GuildChannel.move) async def move(self, **kwargs): kwargs.pop('category', None) await super().move(**kwargs) @property def channels(self) -> List[GuildChannelType]: """List[:class:`abc.GuildChannel`]: Returns the channels that are under this category. These are sorted by the official Discord UI, which places voice channels below the text channels. """ def comparator(channel): return (not isinstance(channel, TextChannel), channel.position) ret = [c for c in self.guild.channels if c.category_id == self.id] ret.sort(key=comparator) return ret @property def text_channels(self) -> List[TextChannel]: """List[:class:`TextChannel`]: Returns the text channels that are under this category.""" ret = [c for c in self.guild.channels if c.category_id == self.id and isinstance(c, TextChannel)] ret.sort(key=lambda c: (c.position, c.id)) return ret @property def voice_channels(self) -> List[VoiceChannel]: """List[:class:`VoiceChannel`]: Returns the voice channels that are under this category.""" ret = [c for c in self.guild.channels if c.category_id == self.id and isinstance(c, VoiceChannel)] ret.sort(key=lambda c: (c.position, c.id)) return ret @property def stage_channels(self) -> List[StageChannel]: """List[:class:`StageChannel`]: Returns the stage channels that are under this category. .. versionadded:: 1.7 """ ret = [c for c in self.guild.channels if c.category_id == self.id and isinstance(c, StageChannel)] ret.sort(key=lambda c: (c.position, c.id)) return ret async def create_text_channel(self, name: str, **options: Any) -> TextChannel: """|coro| A shortcut method to :meth:`Guild.create_text_channel` to create a :class:`TextChannel` in the category. Returns ------- :class:`TextChannel` The channel that was just created. """ return await self.guild.create_text_channel(name, category=self, **options) async def create_voice_channel(self, name: str, **options: Any) -> VoiceChannel: """|coro| A shortcut method to :meth:`Guild.create_voice_channel` to create a :class:`VoiceChannel` in the category. Returns ------- :class:`VoiceChannel` The channel that was just created. """ return await self.guild.create_voice_channel(name, category=self, **options) async def create_stage_channel(self, name: str, **options: Any) -> StageChannel: """|coro| A shortcut method to :meth:`Guild.create_stage_channel` to create a :class:`StageChannel` in the category. .. versionadded:: 1.7 Returns ------- :class:`StageChannel` The channel that was just created. """ return await self.guild.create_stage_channel(name, category=self, **options) class StoreChannel(discord.abc.GuildChannel, Hashable): """Represents a Discord guild store channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns the channel's name. Attributes ----------- name: :class:`str` The channel name. guild: :class:`Guild` The guild the channel belongs to. id: :class:`int` The channel ID. category_id: :class:`int` The category channel ID this channel belongs to. 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. nsfw: :class:`bool` If the channel is marked as "not safe for work". .. note:: To check if the channel or the guild of that channel are marked as NSFW, consider :meth:`is_nsfw` instead. """ __slots__ = ( 'name', 'id', 'guild', '_state', 'nsfw', 'category_id', 'position', '_overwrites', ) def __init__(self, *, state: ConnectionState, guild: Guild, data: StoreChannelPayload): self._state: ConnectionState = state self.id: int = int(data['id']) self._update(guild, data) def __repr__(self) -> str: return f'<StoreChannel id={self.id} name={self.name!r} position={self.position} nsfw={self.nsfw}>' def _update(self, guild: Guild, data: StoreChannelPayload) -> None: self.guild: Guild = guild self.name: str = data['name'] self.category_id: Optional[int] = utils._get_as_snowflake(data, 'parent_id') self.position: int = data['position'] self.nsfw: bool = data.get('nsfw', False) self._fill_overwrites(data) @property def _sorting_bucket(self) -> int: return ChannelType.text.value @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.store @utils.copy_doc(discord.abc.GuildChannel.permissions_for) def permissions_for(self, obj: Union[Member, Role], /) -> Permissions: base = super().permissions_for(obj) # store channels do not have voice related permissions denied = Permissions.voice() base.value &= ~denied.value return base def is_nsfw(self) -> bool: """:class:`bool`: Checks if the channel is NSFW.""" return self.nsfw @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> StoreChannel: return await self._clone_impl({'nsfw': self.nsfw}, name=name, reason=reason) @overload async def edit( self, *, name: str = ..., position: int = ..., nsfw: bool = ..., sync_permissions: bool = ..., category: Optional[CategoryChannel], reason: Optional[str], overwrites: Mapping[Union[Role, Member], PermissionOverwrite], ) -> Optional[StoreChannel]: ... @overload async def edit(self) -> Optional[StoreChannel]: ... async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionchanged:: 2.0 Edits are no longer in-place, the newly edited channel is returned instead. Parameters ---------- name: :class:`str` The new channel name. position: :class:`int` The new channel's position. nsfw: :class:`bool` To mark the channel as NSFW or not. sync_permissions: :class:`bool` Whether to sync permissions with the channel's new or pre-existing category. Defaults to ``False``. category: Optional[:class:`CategoryChannel`] The new category for this channel. Can be ``None`` to remove the category. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. overwrites: :class:`Mapping` A :class:`Mapping` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. .. versionadded:: 1.3 Raises ------ InvalidArgument If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form. Forbidden You do not have permissions to edit the channel. HTTPException Editing the channel failed. Returns -------- Optional[:class:`.StoreChannel`] The newly edited store channel. If the edit was only positional then ``None`` is returned instead. """ payload = await self._edit(options, reason=reason) if payload is not None: # the payload will always be the proper channel payload return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore DMC = TypeVar('DMC', bound='DMChannel') class DMChannel(discord.abc.Messageable, Hashable): """Represents a Discord direct message channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns a string representation of the channel Attributes ---------- recipient: Optional[:class:`User`] The user you are participating with in the direct message channel. If this channel is received through the gateway, the recipient information may not be always available. me: :class:`ClientUser` The user presenting yourself. id: :class:`int` The direct message channel ID. """ __slots__ = ('id', 'recipient', 'me', '_state') def __init__(self, *, me: ClientUser, state: ConnectionState, data: DMChannelPayload): self._state: ConnectionState = state self.recipient: Optional[User] = state.store_user(data['recipients'][0]) self.me: ClientUser = me self.id: int = int(data['id']) async def _get_channel(self): return self def __str__(self) -> str: if self.recipient: return f'Direct Message with {self.recipient}' return 'Direct Message with Unknown User' def __repr__(self) -> str: return f'<DMChannel id={self.id} recipient={self.recipient!r}>' @classmethod def _from_message(cls: Type[DMC], state: ConnectionState, channel_id: int) -> DMC: self: DMC = cls.__new__(cls) self._state = state self.id = channel_id self.recipient = None # state.user won't be None here self.me = state.user # type: ignore return self @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.private @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the direct message channel's creation time in UTC.""" return utils.snowflake_time(self.id) def permissions_for(self, obj: Any = None, /) -> Permissions: """Handles permission resolution for a :class:`User`. This function is there for compatibility with other channel types. Actual direct messages do not really have the concept of permissions. This returns all the Text related permissions set to ``True`` except: - :attr:`~Permissions.send_tts_messages`: You cannot send TTS messages in a DM. - :attr:`~Permissions.manage_messages`: You cannot delete others messages in a DM. Parameters ----------- obj: :class:`User` The user to check permissions for. This parameter is ignored but kept for compatibility with other ``permissions_for`` methods. Returns -------- :class:`Permissions` The resolved permissions. """ base = Permissions.text() base.read_messages = True base.send_tts_messages = False base.manage_messages = False return base 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:: 1.6 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) class GroupChannel(discord.abc.Messageable, Hashable): """Represents a Discord group channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns a string representation of the channel Attributes ---------- recipients: List[:class:`User`] The users you are participating with in the group channel. me: :class:`ClientUser` The user presenting yourself. id: :class:`int` The group channel ID. owner: Optional[:class:`User`] The user that owns the group channel. owner_id: :class:`int` The owner ID that owns the group channel. .. versionadded:: 2.0 name: Optional[:class:`str`] The group channel's name if provided. """ __slots__ = ('id', 'recipients', 'owner_id', 'owner', '_icon', 'name', 'me', '_state') def __init__(self, *, me: ClientUser, state: ConnectionState, data: GroupChannelPayload): self._state: ConnectionState = state self.id: int = int(data['id']) self.me: ClientUser = me self._update_group(data) def _update_group(self, data: GroupChannelPayload) -> None: self.owner_id: Optional[int] = utils._get_as_snowflake(data, 'owner_id') self._icon: Optional[str] = data.get('icon') self.name: Optional[str] = data.get('name') self.recipients: List[User] = [self._state.store_user(u) for u in data.get('recipients', [])] self.owner: Optional[BaseUser] if self.owner_id == self.me.id: self.owner = self.me else: self.owner = utils.find(lambda u: u.id == self.owner_id, self.recipients) async def _get_channel(self): return self def __str__(self) -> str: if self.name: return self.name if len(self.recipients) == 0: return 'Unnamed' return ', '.join(map(lambda x: x.name, self.recipients)) def __repr__(self) -> str: return f'<GroupChannel id={self.id} name={self.name!r}>' @property def type(self) -> ChannelType: """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.group @property def icon(self) -> Optional[Asset]: """Optional[:class:`Asset`]: Returns the channel's icon asset if available.""" if self._icon is None: return None return Asset._from_icon(self._state, self.id, self._icon, path='channel') @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" return utils.snowflake_time(self.id) def permissions_for(self, obj: Snowflake, /) -> Permissions: """Handles permission resolution for a :class:`User`. This function is there for compatibility with other channel types. Actual direct messages do not really have the concept of permissions. This returns all the Text related permissions set to ``True`` except: - :attr:`~Permissions.send_tts_messages`: You cannot send TTS messages in a DM. - :attr:`~Permissions.manage_messages`: You cannot delete others messages in a DM. This also checks the kick_members permission if the user is the owner. Parameters ----------- obj: :class:`~discord.abc.Snowflake` The user to check permissions for. Returns -------- :class:`Permissions` The resolved permissions for the user. """ base = Permissions.text() base.read_messages = True base.send_tts_messages = False base.manage_messages = False base.mention_everyone = True if obj.id == self.owner_id: base.kick_members = True return base async def leave(self) -> None: """|coro| Leave the group. If you are the only one in the group, this deletes it as well. Raises ------- HTTPException Leaving the group failed. """ await self._state.http.leave_group(self.id) class PartialMessageable(discord.abc.Messageable, Hashable): """Represents a partial messageable to aid with working messageable channels when only a channel ID are present. The only way to construct this class is through :meth:`Client.get_partial_messageable`. Note that this class is trimmed down and has no rich attributes. .. versionadded:: 2.0 .. container:: operations .. describe:: x == y Checks if two partial messageables are equal. .. describe:: x != y Checks if two partial messageables are not equal. .. describe:: hash(x) Returns the partial messageable's hash. Attributes ----------- id: :class:`int` The channel ID associated with this partial messageable. type: Optional[:class:`ChannelType`] The channel type associated with this partial messageable, if given. """ def __init__(self, state: ConnectionState, id: int, type: Optional[ChannelType] = None): self._state: ConnectionState = state self._channel: Object = Object(id=id) self.id: int = id self.type: Optional[ChannelType] = type async def _get_channel(self) -> Object: return self._channel 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. 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 _guild_channel_factory(channel_type: int): value = try_enum(ChannelType, channel_type) if value is ChannelType.text: return TextChannel, value elif value is ChannelType.voice: return VoiceChannel, value elif value is ChannelType.category: return CategoryChannel, value elif value is ChannelType.news: return TextChannel, value elif value is ChannelType.store: return StoreChannel, value elif value is ChannelType.stage_voice: return StageChannel, value else: return None, value def _channel_factory(channel_type: int): cls, value = _guild_channel_factory(channel_type) if value is ChannelType.private: return DMChannel, value elif value is ChannelType.group: return GroupChannel, value else: return cls, value 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 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
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/channel.py
channel.py
from __future__ import annotations from typing import Any, List, Optional, TYPE_CHECKING, Union from .utils import snowflake_time, _get_as_snowflake, resolve_invite from .user import BaseUser from .activity import Activity, BaseActivity, Spotify, create_activity from .invite import Invite from .enums import Status, try_enum if TYPE_CHECKING: import datetime from .state import ConnectionState from .types.widget import ( WidgetMember as WidgetMemberPayload, Widget as WidgetPayload, ) __all__ = ( 'WidgetChannel', 'WidgetMember', 'Widget', ) class WidgetChannel: """Represents a "partial" widget channel. .. container:: operations .. describe:: x == y Checks if two partial channels are the same. .. describe:: x != y Checks if two partial channels are not the same. .. describe:: hash(x) Return the partial channel's hash. .. describe:: str(x) Returns the partial channel's name. Attributes ----------- id: :class:`int` The channel's ID. name: :class:`str` The channel's name. position: :class:`int` The channel's position """ __slots__ = ('id', 'name', 'position') def __init__(self, id: int, name: str, position: int) -> None: self.id: int = id self.name: str = name self.position: int = position def __str__(self) -> str: return self.name def __repr__(self) -> str: return f'<WidgetChannel id={self.id} name={self.name!r} position={self.position!r}>' @property def mention(self) -> str: """:class:`str`: The string that allows you to mention the channel.""" return f'<#{self.id}>' @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" return snowflake_time(self.id) class WidgetMember(BaseUser): """Represents a "partial" member of the widget's guild. .. container:: operations .. describe:: x == y Checks if two widget members are the same. .. describe:: x != y Checks if two widget members are not the same. .. describe:: hash(x) Return the widget member's hash. .. describe:: str(x) Returns the widget member's `name#discriminator`. Attributes ----------- id: :class:`int` The member's ID. name: :class:`str` The member's username. discriminator: :class:`str` The member's discriminator. bot: :class:`bool` Whether the member is a bot. status: :class:`Status` The member's status. nick: Optional[:class:`str`] The member's nickname. avatar: Optional[:class:`str`] The member's avatar hash. activity: Optional[Union[:class:`BaseActivity`, :class:`Spotify`]] The member's activity. deafened: Optional[:class:`bool`] Whether the member is currently deafened. muted: Optional[:class:`bool`] Whether the member is currently muted. suppress: Optional[:class:`bool`] Whether the member is currently being suppressed. connected_channel: Optional[:class:`WidgetChannel`] Which channel the member is connected to. """ __slots__ = ('name', 'status', 'nick', 'avatar', 'discriminator', 'id', 'bot', 'activity', 'deafened', 'suppress', 'muted', 'connected_channel') if TYPE_CHECKING: activity: Optional[Union[BaseActivity, Spotify]] def __init__( self, *, state: ConnectionState, data: WidgetMemberPayload, connected_channel: Optional[WidgetChannel] = None ) -> None: super().__init__(state=state, data=data) self.nick: Optional[str] = data.get('nick') self.status: Status = try_enum(Status, data.get('status')) self.deafened: Optional[bool] = data.get('deaf', False) or data.get('self_deaf', False) self.muted: Optional[bool] = data.get('mute', False) or data.get('self_mute', False) self.suppress: Optional[bool] = data.get('suppress', False) try: game = data['game'] except KeyError: activity = None else: activity = create_activity(game) self.activity: Optional[Union[BaseActivity, Spotify]] = activity self.connected_channel: Optional[WidgetChannel] = connected_channel def __repr__(self) -> str: return ( f"<WidgetMember name={self.name!r} discriminator={self.discriminator!r}" f" bot={self.bot} nick={self.nick!r}>" ) @property def display_name(self) -> str: """:class:`str`: Returns the member's display name.""" return self.nick or self.name class Widget: """Represents a :class:`Guild` widget. .. container:: operations .. describe:: x == y Checks if two widgets are the same. .. describe:: x != y Checks if two widgets are not the same. .. describe:: str(x) Returns the widget's JSON URL. Attributes ----------- id: :class:`int` The guild's ID. name: :class:`str` The guild's name. channels: List[:class:`WidgetChannel`] The accessible voice channels in the guild. members: List[:class:`Member`] The online members in the server. Offline members do not appear in the widget. .. note:: Due to a Discord limitation, if this data is available the users will be "anonymized" with linear IDs and discriminator information being incorrect. Likewise, the number of members retrieved is capped. """ __slots__ = ('_state', 'channels', '_invite', 'id', 'members', 'name') def __init__(self, *, state: ConnectionState, data: WidgetPayload) -> None: self._state = state self._invite = data['instant_invite'] self.name: str = data['name'] self.id: int = int(data['id']) self.channels: List[WidgetChannel] = [] for channel in data.get('channels', []): _id = int(channel['id']) self.channels.append(WidgetChannel(id=_id, name=channel['name'], position=channel['position'])) self.members: List[WidgetMember] = [] channels = {channel.id: channel for channel in self.channels} for member in data.get('members', []): connected_channel = _get_as_snowflake(member, 'channel_id') if connected_channel in channels: connected_channel = channels[connected_channel] # type: ignore elif connected_channel: connected_channel = WidgetChannel(id=connected_channel, name='', position=0) self.members.append(WidgetMember(state=self._state, data=member, connected_channel=connected_channel)) # type: ignore def __str__(self) -> str: return self.json_url def __eq__(self, other: Any) -> bool: if isinstance(other, Widget): return self.id == other.id return False def __repr__(self) -> str: return f'<Widget id={self.id} name={self.name!r} invite_url={self.invite_url!r}>' @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the member's creation time in UTC.""" return snowflake_time(self.id) @property def json_url(self) -> str: """:class:`str`: The JSON URL of the widget.""" return f"https://discord.com/api/guilds/{self.id}/widget.json" @property def invite_url(self) -> str: """Optional[:class:`str`]: The invite URL for the guild, if available.""" return self._invite async def fetch_invite(self, *, with_counts: bool = True) -> Invite: """|coro| Retrieves an :class:`Invite` from the widget's invite URL. This is the same as :meth:`Client.fetch_invite`; the invite code is abstracted away. Parameters ----------- with_counts: :class:`bool` Whether to include count information in the invite. This fills the :attr:`Invite.approximate_member_count` and :attr:`Invite.approximate_presence_count` fields. Returns -------- :class:`Invite` The invite from the widget's invite URL. """ invite_id = resolve_invite(self._invite) data = await self._state.http.get_invite(invite_id, with_counts=with_counts) return Invite.from_incomplete(state=self._state, data=data)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/widget.py
widget.py
from __future__ import annotations import asyncio import logging import signal import sys import traceback from typing import Any, Callable, Coroutine, Dict, Generator, List, Optional, Sequence, TYPE_CHECKING, Tuple, TypeVar, Union import aiohttp from .user import User, ClientUser from .invite import Invite from .template import Template from .widget import Widget from .guild import Guild from .emoji import Emoji from .channel import _threaded_channel_factory, PartialMessageable from .enums import ChannelType from .mentions import AllowedMentions from .errors import * from .enums import Status, VoiceRegion from .flags import ApplicationFlags, Intents from .gateway import * from .activity import ActivityTypes, BaseActivity, create_activity from .voice_client import VoiceClient from .http import HTTPClient from .state import ConnectionState from . import utils from .utils import MISSING from .object import Object from .backoff import ExponentialBackoff from .webhook import Webhook from .iterators import GuildIterator from .appinfo import AppInfo from .ui.view import View from .stage_instance import StageInstance from .threads import Thread from .sticker import GuildSticker, StandardSticker, StickerPack, _sticker_factory if TYPE_CHECKING: from .abc import SnowflakeTime, PrivateChannel, GuildChannel, Snowflake from .channel import DMChannel from .message import Message from .member import Member from .voice_client import VoiceProtocol __all__ = ( 'Client', ) Coro = TypeVar('Coro', bound=Callable[..., Coroutine[Any, Any, Any]]) _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 }) 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() class Client: r"""Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API. A number of options can be passed to the :class:`Client`. Parameters ----------- max_messages: Optional[:class:`int`] The maximum number of messages to store in the internal message cache. This defaults to ``1000``. Passing in ``None`` disables the message cache. .. versionchanged:: 1.3 Allow disabling the message cache and change the default size to ``1000``. loop: Optional[:class:`asyncio.AbstractEventLoop`] The :class:`asyncio.AbstractEventLoop` to use for asynchronous operations. Defaults to ``None``, in which case the default event loop is used via :func:`asyncio.get_event_loop()`. connector: Optional[:class:`aiohttp.BaseConnector`] The connector to use for connection pooling. proxy: Optional[:class:`str`] Proxy URL. proxy_auth: Optional[:class:`aiohttp.BasicAuth`] An object that represents proxy HTTP Basic Authorization. shard_id: Optional[:class:`int`] Integer starting at ``0`` and less than :attr:`.shard_count`. shard_count: Optional[:class:`int`] The total number of shards. application_id: :class:`int` The client's application ID. intents: :class:`Intents` The intents that you want to enable for the session. This is a way of disabling and enabling certain gateway events from triggering and being sent. If not given, defaults to a regularly constructed :class:`Intents` class. .. versionadded:: 1.5 member_cache_flags: :class:`MemberCacheFlags` Allows for finer control over how the library caches members. If not given, defaults to cache as much as possible with the currently selected intents. .. versionadded:: 1.5 chunk_guilds_at_startup: :class:`bool` Indicates if :func:`.on_ready` should be delayed to chunk all guilds at start-up if necessary. This operation is incredibly slow for large amounts of guilds. The default is ``True`` if :attr:`Intents.members` is ``True``. .. versionadded:: 1.5 status: Optional[:class:`.Status`] A status to start your presence with upon logging on to Discord. activity: Optional[:class:`.BaseActivity`] An activity to start your presence with upon logging on to Discord. allowed_mentions: Optional[:class:`AllowedMentions`] Control how the client handles mentions by default on every message sent. .. versionadded:: 1.4 heartbeat_timeout: :class:`float` The maximum numbers of seconds before timing out and restarting the WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if processing the initial packets take too long to the point of disconnecting you. The default timeout is 60 seconds. guild_ready_timeout: :class:`float` The maximum number of seconds to wait for the GUILD_CREATE stream to end before preparing the member cache and firing READY. The default timeout is 2 seconds. .. versionadded:: 1.4 assume_unsync_clock: :class:`bool` Whether to assume the system clock is unsynced. This applies to the ratelimit handling code. If this is set to ``True``, the default, then the library uses the time to reset a rate limit bucket given by Discord. If this is ``False`` then your system clock is used to calculate how long to sleep for. If this is set to ``False`` it is recommended to sync your system clock to Google's NTP server. .. versionadded:: 1.3 enable_debug_events: :class:`bool` Whether to enable events that are useful only for debugging gateway related information. Right now this involves :func:`on_socket_raw_receive` and :func:`on_socket_raw_send`. If this is ``False`` then those events will not be dispatched (due to performance considerations). To enable these events, this must be set to ``True``. Defaults to ``False``. .. versionadded:: 2.0 Attributes ----------- ws The websocket gateway the client is currently connected to. Could be ``None``. loop: :class:`asyncio.AbstractEventLoop` The event loop that the client uses for asynchronous operations. """ def __init__( self, *, loop: Optional[asyncio.AbstractEventLoop] = None, **options: Any, ): # self.ws is set in the connect method self.ws: DiscordWebSocket = None # type: ignore self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() if loop is None else loop self._listeners: Dict[str, List[Tuple[asyncio.Future, Callable[..., bool]]]] = {} self.shard_id: Optional[int] = options.get('shard_id') self.shard_count: Optional[int] = options.get('shard_count') connector: Optional[aiohttp.BaseConnector] = options.pop('connector', None) proxy: Optional[str] = options.pop('proxy', None) proxy_auth: Optional[aiohttp.BasicAuth] = options.pop('proxy_auth', None) unsync_clock: bool = options.pop('assume_unsync_clock', True) self.http: HTTPClient = HTTPClient(connector, proxy=proxy, proxy_auth=proxy_auth, unsync_clock=unsync_clock, loop=self.loop) self._handlers: Dict[str, Callable] = { 'ready': self._handle_ready } self._hooks: Dict[str, Callable] = { 'before_identify': self._call_before_identify_hook } self._enable_debug_events: bool = options.pop('enable_debug_events', False) self._connection: ConnectionState = self._get_state(**options) self._connection.shard_count = self.shard_count self._closed: bool = False self._ready: asyncio.Event = asyncio.Event() self._connection._get_websocket = self._get_websocket self._connection._get_client = lambda: self if VoiceClient.warn_nacl: VoiceClient.warn_nacl = False _log.warning("PyNaCl is not installed, voice will NOT be supported") # internals def _get_websocket(self, guild_id: Optional[int] = None, *, shard_id: Optional[int] = None) -> DiscordWebSocket: return self.ws def _get_state(self, **options: Any) -> ConnectionState: return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, loop=self.loop, **options) def _handle_ready(self) -> None: self._ready.set() @property def latency(self) -> float: """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This could be referred to as the Discord WebSocket protocol latency. """ ws = self.ws return float('nan') if not ws else ws.latency def is_ws_ratelimited(self) -> bool: """:class:`bool`: Whether the websocket is currently rate limited. This can be useful to know when deciding whether you should query members using HTTP or via the gateway. .. versionadded:: 1.6 """ if self.ws: return self.ws.is_ratelimited() return False @property def user(self) -> Optional[ClientUser]: """Optional[:class:`.ClientUser`]: Represents the connected client. ``None`` if not logged in.""" return self._connection.user @property def guilds(self) -> List[Guild]: """List[:class:`.Guild`]: The guilds that the connected client is a member of.""" return self._connection.guilds @property def emojis(self) -> List[Emoji]: """List[:class:`.Emoji`]: The emojis that the connected client has.""" return self._connection.emojis @property def stickers(self) -> List[GuildSticker]: """List[:class:`.GuildSticker`]: The stickers that the connected client has. .. versionadded:: 2.0 """ return self._connection.stickers @property def cached_messages(self) -> Sequence[Message]: """Sequence[:class:`.Message`]: Read-only list of messages the connected client has cached. .. versionadded:: 1.1 """ return utils.SequenceProxy(self._connection._messages or []) @property def private_channels(self) -> List[PrivateChannel]: """List[:class:`.abc.PrivateChannel`]: The private channels that the connected client is participating on. .. note:: This returns only up to 128 most recent private channels due to an internal working on how Discord deals with private channels. """ return self._connection.private_channels @property def voice_clients(self) -> List[VoiceProtocol]: """List[:class:`.VoiceProtocol`]: Represents a list of voice connections. These are usually :class:`.VoiceClient` instances. """ return self._connection.voice_clients @property def application_id(self) -> Optional[int]: """Optional[:class:`int`]: The client's application ID. If this is not passed via ``__init__`` then this is retrieved through the gateway when an event contains the data. Usually after :func:`~discord.on_connect` is called. .. versionadded:: 2.0 """ return self._connection.application_id @property def application_flags(self) -> ApplicationFlags: """:class:`~discord.ApplicationFlags`: The client's application flags. .. versionadded:: 2.0 """ return self._connection.application_flags # type: ignore def is_ready(self) -> bool: """:class:`bool`: Specifies if the client's internal cache is ready for use.""" return self._ready.is_set() async def _run_event(self, coro: Callable[..., Coroutine[Any, Any, Any]], event_name: str, *args: Any, **kwargs: Any) -> None: try: await coro(*args, **kwargs) except asyncio.CancelledError: pass except Exception: try: await self.on_error(event_name, *args, **kwargs) except asyncio.CancelledError: pass def _schedule_event(self, coro: Callable[..., Coroutine[Any, Any, Any]], event_name: str, *args: Any, **kwargs: Any) -> asyncio.Task: wrapped = self._run_event(coro, event_name, *args, **kwargs) # Schedules the task return asyncio.create_task(wrapped, name=f'discord.py: {event_name}') def dispatch(self, event: str, *args: Any, **kwargs: Any) -> None: _log.debug('Dispatching event %s', event) method = 'on_' + event listeners = self._listeners.get(event) if listeners: removed = [] for i, (future, condition) in enumerate(listeners): if future.cancelled(): removed.append(i) continue try: result = condition(*args) except Exception as exc: future.set_exception(exc) removed.append(i) else: if result: if len(args) == 0: future.set_result(None) elif len(args) == 1: future.set_result(args[0]) else: future.set_result(args) removed.append(i) if len(removed) == len(listeners): self._listeners.pop(event) else: for idx in reversed(removed): del listeners[idx] try: coro = getattr(self, method) except AttributeError: pass else: self._schedule_event(coro, method, *args, **kwargs) async def on_error(self, event_method: str, *args: Any, **kwargs: Any) -> None: """|coro| The default error handler provided by the client. By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. Check :func:`~discord.on_error` for more details. """ print(f'Ignoring exception in {event_method}', file=sys.stderr) traceback.print_exc() # hooks async def _call_before_identify_hook(self, shard_id: Optional[int], *, initial: bool = False) -> None: # This hook is an internal hook that actually calls the public one. # It allows the library to have its own hook without stepping on the # toes of those who need to override their own hook. await self.before_identify_hook(shard_id, initial=initial) async def before_identify_hook(self, shard_id: Optional[int], *, initial: bool = False) -> None: """|coro| A hook that is called before IDENTIFYing a session. This is useful if you wish to have more control over the synchronization of multiple IDENTIFYing clients. The default implementation sleeps for 5 seconds. .. versionadded:: 1.4 Parameters ------------ shard_id: :class:`int` The shard ID that requested being IDENTIFY'd initial: :class:`bool` Whether this IDENTIFY is the first initial IDENTIFY. """ if not initial: await asyncio.sleep(5.0) # login state management async def login(self, token: str) -> None: """|coro| Logs in the client with the specified credentials. Parameters ----------- token: :class:`str` The authentication token. Do not prefix this token with anything as the library will do it for you. Raises ------ :exc:`.LoginFailure` The wrong credentials are passed. :exc:`.HTTPException` An unknown HTTP related error occurred, usually when it isn't 200 or the known incorrect credentials passing status code. """ _log.info('logging in using static token') data = await self.http.static_login(token.strip()) self._connection.user = ClientUser(state=self._connection, data=data) async def connect(self, *, reconnect: bool = True) -> None: """|coro| Creates a websocket connection and lets the websocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated. Parameters ----------- reconnect: :class:`bool` If we should attempt reconnecting, either due to internet failure or a specific failure on Discord's part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens). Raises ------- :exc:`.GatewayNotFound` If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage. :exc:`.ConnectionClosed` The websocket connection has been terminated. """ backoff = ExponentialBackoff() ws_params = { 'initial': True, 'shard_id': self.shard_id, } while not self.is_closed(): try: coro = DiscordWebSocket.from_client(self, **ws_params) self.ws = await asyncio.wait_for(coro, timeout=60.0) ws_params['initial'] = False while True: await self.ws.poll_event() except ReconnectWebSocket as e: _log.info('Got a request to %s the websocket.', e.op) self.dispatch('disconnect') ws_params.update(sequence=self.ws.sequence, resume=e.resume, session=self.ws.session_id) continue except (OSError, HTTPException, GatewayNotFound, ConnectionClosed, aiohttp.ClientError, asyncio.TimeoutError) as exc: self.dispatch('disconnect') if not reconnect: await self.close() if isinstance(exc, ConnectionClosed) and exc.code == 1000: # clean close, don't re-raise this return raise if self.is_closed(): return # If we get connection reset by peer then try to RESUME if isinstance(exc, OSError) and exc.errno in (54, 10054): ws_params.update(sequence=self.ws.sequence, initial=False, resume=True, session=self.ws.session_id) continue # We should only get this when an unhandled close code happens, # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc) # sometimes, discord sends us 1000 for unknown reasons so we should reconnect # regardless and rely on is_closed instead if isinstance(exc, ConnectionClosed): if exc.code == 4014: raise PrivilegedIntentsRequired(exc.shard_id) from None if exc.code != 1000: await self.close() raise retry = backoff.delay() _log.exception("Attempting a reconnect in %.2fs", retry) await asyncio.sleep(retry) # Always try to RESUME the connection # If the connection is not RESUME-able then the gateway will invalidate the session. # This is apparently what the official Discord client does. ws_params.update(sequence=self.ws.sequence, resume=True, session=self.ws.session_id) async def close(self) -> None: """|coro| Closes the connection to Discord. """ if self._closed: return self._closed = True for voice in self.voice_clients: try: await voice.disconnect(force=True) except Exception: # if an error happens during disconnects, disregard it. pass if self.ws is not None and self.ws.open: await self.ws.close(code=1000) await self.http.close() self._ready.clear() def clear(self) -> None: """Clears the internal state of the bot. After this, the bot can be considered "re-opened", i.e. :meth:`is_closed` and :meth:`is_ready` both return ``False`` along with the bot's internal cache cleared. """ self._closed = False self._ready.clear() self._connection.clear() self.http.recreate() async def start(self, token: str, *, reconnect: bool = True) -> None: """|coro| A shorthand coroutine for :meth:`login` + :meth:`connect`. Raises ------- TypeError An unexpected keyword argument was received. """ await self.login(token) await self.connect(reconnect=reconnect) def run(self, *args: Any, **kwargs: Any) -> None: """A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then this function should not be used. Use :meth:`start` coroutine or :meth:`connect` + :meth:`login`. Roughly Equivalent to: :: try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(close()) # cancel all tasks lingering finally: loop.close() .. warning:: This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns. """ loop = self.loop try: loop.add_signal_handler(signal.SIGINT, lambda: loop.stop()) loop.add_signal_handler(signal.SIGTERM, lambda: loop.stop()) except NotImplementedError: pass async def runner(): try: await self.start(*args, **kwargs) finally: if not self.is_closed(): await self.close() def stop_loop_on_completion(f): loop.stop() future = asyncio.ensure_future(runner(), loop=loop) future.add_done_callback(stop_loop_on_completion) try: loop.run_forever() except KeyboardInterrupt: _log.info('Received signal to terminate bot and event loop.') finally: future.remove_done_callback(stop_loop_on_completion) _log.info('Cleaning up tasks.') _cleanup_loop(loop) if not future.cancelled(): try: return future.result() except KeyboardInterrupt: # I am unsure why this gets raised here but suppress it anyway return None # properties def is_closed(self) -> bool: """:class:`bool`: Indicates if the websocket connection is closed.""" return self._closed @property def activity(self) -> Optional[ActivityTypes]: """Optional[:class:`.BaseActivity`]: The activity being used upon logging in. """ return create_activity(self._connection._activity) @activity.setter def activity(self, value: Optional[ActivityTypes]) -> None: if value is None: self._connection._activity = None elif isinstance(value, BaseActivity): # ConnectionState._activity is typehinted as ActivityPayload, we're passing Dict[str, Any] self._connection._activity = value.to_dict() # type: ignore else: raise TypeError('activity must derive from BaseActivity.') @property def status(self): """:class:`.Status`: The status being used upon logging on to Discord. .. versionadded: 2.0 """ if self._connection._status in set(state.value for state in Status): return Status(self._connection._status) return Status.online @status.setter def status(self, value): if value is Status.offline: self._connection._status = 'invisible' elif isinstance(value, Status): self._connection._status = str(value) else: raise TypeError('status must derive from Status.') @property def allowed_mentions(self) -> Optional[AllowedMentions]: """Optional[:class:`~discord.AllowedMentions`]: The allowed mention configuration. .. versionadded:: 1.4 """ return self._connection.allowed_mentions @allowed_mentions.setter def allowed_mentions(self, value: Optional[AllowedMentions]) -> None: if value is None or isinstance(value, AllowedMentions): self._connection.allowed_mentions = value else: raise TypeError(f'allowed_mentions must be AllowedMentions not {value.__class__!r}') @property def intents(self) -> Intents: """:class:`~discord.Intents`: The intents configured for this connection. .. versionadded:: 1.5 """ return self._connection.intents # helpers/getters @property def users(self) -> List[User]: """List[:class:`~discord.User`]: Returns a list of all the users the bot can see.""" return list(self._connection._users.values()) def get_channel(self, id: int, /) -> Optional[Union[GuildChannel, Thread, PrivateChannel]]: """Returns a channel or thread with the given ID. Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[Union[:class:`.abc.GuildChannel`, :class:`.Thread`, :class:`.abc.PrivateChannel`]] The returned channel or ``None`` if not found. """ return self._connection.get_channel(id) def get_partial_messageable(self, id: int, *, type: Optional[ChannelType] = None) -> PartialMessageable: """Returns a partial messageable with the given channel ID. This is useful if you have a channel_id but don't want to do an API call to send messages to it. .. versionadded:: 2.0 Parameters ----------- id: :class:`int` The channel ID to create a partial messageable for. type: Optional[:class:`.ChannelType`] The underlying channel type for the partial messageable. Returns -------- :class:`.PartialMessageable` The partial messageable """ return PartialMessageable(state=self._connection, id=id, type=type) def get_stage_instance(self, id: int, /) -> Optional[StageInstance]: """Returns a stage instance with the given stage channel ID. .. versionadded:: 2.0 Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[:class:`.StageInstance`] The returns stage instance of ``None`` if not found. """ from .channel import StageChannel channel = self._connection.get_channel(id) if isinstance(channel, StageChannel): return channel.instance def get_guild(self, id: int, /) -> Optional[Guild]: """Returns a guild with the given ID. Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[:class:`.Guild`] The guild or ``None`` if not found. """ return self._connection._get_guild(id) def get_user(self, id: int, /) -> Optional[User]: """Returns a user with the given ID. Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[:class:`~discord.User`] The user or ``None`` if not found. """ return self._connection.get_user(id) def get_emoji(self, id: int, /) -> Optional[Emoji]: """Returns an emoji with the given ID. Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[:class:`.Emoji`] The custom emoji or ``None`` if not found. """ return self._connection.get_emoji(id) def get_sticker(self, id: int, /) -> Optional[GuildSticker]: """Returns a guild sticker with the given ID. .. versionadded:: 2.0 .. note:: To retrieve standard stickers, use :meth:`.fetch_sticker`. or :meth:`.fetch_premium_sticker_packs`. Returns -------- Optional[:class:`.GuildSticker`] The sticker or ``None`` if not found. """ return self._connection.get_sticker(id) def get_all_channels(self) -> Generator[GuildChannel, None, None]: """A generator that retrieves every :class:`.abc.GuildChannel` the client can 'access'. This is equivalent to: :: for guild in client.guilds: for channel in guild.channels: yield channel .. note:: Just because you receive a :class:`.abc.GuildChannel` does not mean that you can communicate in said channel. :meth:`.abc.GuildChannel.permissions_for` should be used for that. Yields ------ :class:`.abc.GuildChannel` A channel the client can 'access'. """ for guild in self.guilds: yield from guild.channels def get_all_members(self) -> Generator[Member, None, None]: """Returns a generator with every :class:`.Member` the client can see. This is equivalent to: :: for guild in client.guilds: for member in guild.members: yield member Yields ------ :class:`.Member` A member the client can see. """ for guild in self.guilds: yield from guild.members # listeners/waiters async def wait_until_ready(self) -> None: """|coro| Waits until the client's internal cache is all ready. """ await self._ready.wait() def wait_for( self, event: str, *, check: Optional[Callable[..., bool]] = None, timeout: Optional[float] = None, ) -> Any: """|coro| Waits for a WebSocket event to be dispatched. This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way. The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default, it does not timeout. Note that this does propagate the :exc:`asyncio.TimeoutError` for you in case of timeout and is provided for ease of use. In case the event returns multiple arguments, a :class:`tuple` containing those arguments is returned instead. Please check the :ref:`documentation <discord-api-events>` for a list of events and their parameters. This function returns the **first event that meets the requirements**. Examples --------- Waiting for a user reply: :: @client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send(f'Hello {msg.author}!') Waiting for a thumbs up reaction from the message author: :: @client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that \N{THUMBS UP SIGN} reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('\N{THUMBS DOWN SIGN}') else: await channel.send('\N{THUMBS UP SIGN}') Parameters ------------ event: :class:`str` The event name, similar to the :ref:`event reference <discord-api-events>`, but without the ``on_`` prefix, to wait for. check: Optional[Callable[..., :class:`bool`]] A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for. timeout: Optional[:class:`float`] The number of seconds to wait before timing out and raising :exc:`asyncio.TimeoutError`. Raises ------- asyncio.TimeoutError If a timeout is provided and it was reached. Returns -------- Any Returns no arguments, a single argument, or a :class:`tuple` of multiple arguments that mirrors the parameters passed in the :ref:`event reference <discord-api-events>`. """ future = self.loop.create_future() if check is None: def _check(*args): return True check = _check ev = event.lower() try: listeners = self._listeners[ev] except KeyError: listeners = [] self._listeners[ev] = listeners listeners.append((future, check)) return asyncio.wait_for(future, timeout) # event registration def event(self, coro: Coro) -> Coro: """A decorator that registers an event to listen to. You can find more info about the events on the :ref:`documentation below <discord-api-events>`. The events must be a :ref:`coroutine <coroutine>`, if not, :exc:`TypeError` is raised. Example --------- .. code-block:: python3 @client.event async def on_ready(): print('Ready!') Raises -------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('event registered must be a coroutine function') setattr(self, coro.__name__, coro) _log.debug('%s has successfully been registered as an event', coro.__name__) return coro async def change_presence( self, *, activity: Optional[BaseActivity] = None, status: Optional[Status] = None, ): """|coro| Changes the client's presence. Example --------- .. code-block:: python3 game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) .. versionchanged:: 2.0 Removed the ``afk`` keyword-only parameter. Parameters ---------- activity: Optional[:class:`.BaseActivity`] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`.Status`] Indicates what status to change to. If ``None``, then :attr:`.Status.online` is used. Raises ------ :exc:`.InvalidArgument` If the ``activity`` parameter is not the proper type. """ if status is None: status_str = 'online' status = Status.online elif status is Status.offline: status_str = 'invisible' status = Status.offline else: status_str = str(status) await self.ws.change_presence(activity=activity, status=status_str) for guild in self._connection.guilds: me = guild.me if me is None: continue if activity is not None: me.activities = (activity,) else: me.activities = () me.status = status # Guild stuff def fetch_guilds( self, *, limit: Optional[int] = 100, before: SnowflakeTime = None, after: SnowflakeTime = None ) -> GuildIterator: """Retrieves an :class:`.AsyncIterator` that enables receiving your guilds. .. note:: Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`, :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`. .. note:: This method is an API call. For general usage, consider :attr:`guilds` instead. Examples --------- Usage :: async for guild in client.fetch_guilds(limit=150): print(guild.name) Flattening into a list :: guilds = await client.fetch_guilds(limit=150).flatten() # guilds is now a list of Guild... All parameters are optional. Parameters ----------- limit: Optional[:class:`int`] The number of guilds to retrieve. If ``None``, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to ``100``. before: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`] Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. after: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`] Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. Raises ------ :exc:`.HTTPException` Getting the guilds failed. Yields -------- :class:`.Guild` The guild with the guild data parsed. """ return GuildIterator(self, limit=limit, before=before, after=after) async def fetch_template(self, code: Union[Template, str]) -> Template: """|coro| Gets a :class:`.Template` from a discord.new URL or code. Parameters ----------- code: Union[:class:`.Template`, :class:`str`] The Discord Template Code or URL (must be a discord.new URL). Raises ------- :exc:`.NotFound` The template is invalid. :exc:`.HTTPException` Getting the template failed. Returns -------- :class:`.Template` The template from the URL/code. """ code = utils.resolve_template(code) data = await self.http.get_template(code) return Template(data=data, state=self._connection) # type: ignore async def fetch_guild(self, guild_id: int, /) -> Guild: """|coro| Retrieves a :class:`.Guild` from an ID. .. note:: Using this, you will **not** receive :attr:`.Guild.channels`, :attr:`.Guild.members`, :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`. .. note:: This method is an API call. For general usage, consider :meth:`get_guild` instead. Parameters ----------- guild_id: :class:`int` The guild's ID to fetch from. Raises ------ :exc:`.Forbidden` You do not have access to the guild. :exc:`.HTTPException` Getting the guild failed. Returns -------- :class:`.Guild` The guild from the ID. """ data = await self.http.get_guild(guild_id) return Guild(data=data, state=self._connection) async def create_guild( self, *, name: str, region: Union[VoiceRegion, str] = VoiceRegion.us_west, icon: bytes = MISSING, code: str = MISSING, ) -> Guild: """|coro| Creates a :class:`.Guild`. Bot accounts in more than 10 guilds are not allowed to create guilds. Parameters ---------- name: :class:`str` The name of the guild. region: :class:`.VoiceRegion` The region for the voice communication server. Defaults to :attr:`.VoiceRegion.us_west`. icon: Optional[:class:`bytes`] The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit` for more details on what is expected. code: :class:`str` The code for a template to create the guild with. .. versionadded:: 1.4 Raises ------ :exc:`.HTTPException` Guild creation failed. :exc:`.InvalidArgument` Invalid icon image format given. Must be PNG or JPG. Returns ------- :class:`.Guild` The guild created. This is not the same guild that is added to cache. """ if icon is not MISSING: icon_base64 = utils._bytes_to_base64_data(icon) else: icon_base64 = None region_value = str(region) if code: data = await self.http.create_from_template(code, name, region_value, icon_base64) else: data = await self.http.create_guild(name, region_value, icon_base64) return Guild(data=data, state=self._connection) async def fetch_stage_instance(self, channel_id: int, /) -> StageInstance: """|coro| Gets a :class:`.StageInstance` for a stage channel id. .. versionadded:: 2.0 Parameters ----------- channel_id: :class:`int` The stage channel ID. Raises ------- :exc:`.NotFound` The stage instance or channel could not be found. :exc:`.HTTPException` Getting the stage instance failed. Returns -------- :class:`.StageInstance` The stage instance from the stage channel ID. """ data = await self.http.get_stage_instance(channel_id) guild = self.get_guild(int(data['guild_id'])) return StageInstance(guild=guild, state=self._connection, data=data) # type: ignore # Invite management async def fetch_invite(self, url: Union[Invite, str], *, with_counts: bool = True, with_expiration: bool = True) -> Invite: """|coro| Gets an :class:`.Invite` from a discord.gg URL or ID. .. note:: If the invite is for a guild you have not joined, the guild and channel attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` and :class:`.PartialInviteChannel` respectively. Parameters ----------- url: Union[:class:`.Invite`, :class:`str`] The Discord invite ID or URL (must be a discord.gg URL). with_counts: :class:`bool` Whether to include count information in the invite. This fills the :attr:`.Invite.approximate_member_count` and :attr:`.Invite.approximate_presence_count` fields. with_expiration: :class:`bool` Whether to include the expiration date of the invite. This fills the :attr:`.Invite.expires_at` field. .. versionadded:: 2.0 Raises ------- :exc:`.NotFound` The invite has expired or is invalid. :exc:`.HTTPException` Getting the invite failed. Returns -------- :class:`.Invite` The invite from the URL/ID. """ invite_id = utils.resolve_invite(url) data = await self.http.get_invite(invite_id, with_counts=with_counts, with_expiration=with_expiration) return Invite.from_incomplete(state=self._connection, data=data) async def delete_invite(self, invite: Union[Invite, str]) -> None: """|coro| Revokes an :class:`.Invite`, URL, or ID to an invite. You must have the :attr:`~.Permissions.manage_channels` permission in the associated guild to do this. Parameters ---------- invite: Union[:class:`.Invite`, :class:`str`] The invite to revoke. Raises ------- :exc:`.Forbidden` You do not have permissions to revoke invites. :exc:`.NotFound` The invite is invalid or expired. :exc:`.HTTPException` Revoking the invite failed. """ invite_id = utils.resolve_invite(invite) await self.http.delete_invite(invite_id) # Miscellaneous stuff async def fetch_widget(self, guild_id: int, /) -> Widget: """|coro| Gets a :class:`.Widget` from a guild ID. .. note:: The guild must have the widget enabled to get this information. Parameters ----------- guild_id: :class:`int` The ID of the guild. Raises ------- :exc:`.Forbidden` The widget for this guild is disabled. :exc:`.HTTPException` Retrieving the widget failed. Returns -------- :class:`.Widget` The guild's widget. """ data = await self.http.get_widget(guild_id) return Widget(state=self._connection, data=data) async def application_info(self) -> AppInfo: """|coro| Retrieves the bot's application information. Raises ------- :exc:`.HTTPException` Retrieving the information failed somehow. Returns -------- :class:`.AppInfo` The bot's application information. """ data = await self.http.application_info() if 'rpc_origins' not in data: data['rpc_origins'] = None return AppInfo(self._connection, data) async def fetch_user(self, user_id: int, /) -> User: """|coro| Retrieves a :class:`~discord.User` based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do. .. note:: This method is an API call. If you have :attr:`discord.Intents.members` and member cache enabled, consider :meth:`get_user` instead. Parameters ----------- user_id: :class:`int` The user's ID to fetch from. Raises ------- :exc:`.NotFound` A user with this ID does not exist. :exc:`.HTTPException` Fetching the user failed. Returns -------- :class:`~discord.User` The user you requested. """ data = await self.http.get_user(user_id) return User(state=self._connection, data=data) async def fetch_channel(self, channel_id: int, /) -> Union[GuildChannel, PrivateChannel, Thread]: """|coro| Retrieves a :class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`, or :class:`.Thread` with the specified ID. .. note:: This method is an API call. For general usage, consider :meth:`get_channel` instead. .. versionadded:: 1.2 Raises ------- :exc:`.InvalidData` An unknown channel type was received from Discord. :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:`.abc.PrivateChannel`, :class:`.Thread`] The channel from the ID. """ data = await self.http.get_channel(channel_id) factory, ch_type = _threaded_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): # the factory will be a DMChannel or GroupChannel here channel = factory(me=self.user, data=data, state=self._connection) # type: ignore else: # the factory can't be a DMChannel or GroupChannel here guild_id = int(data['guild_id']) # type: ignore guild = self.get_guild(guild_id) or Object(id=guild_id) # GuildChannels expect a Guild, we may be passing an Object channel = factory(guild=guild, state=self._connection, data=data) # type: ignore return channel async def fetch_webhook(self, webhook_id: int, /) -> Webhook: """|coro| Retrieves a :class:`.Webhook` with the specified ID. Raises -------- :exc:`.HTTPException` Retrieving the webhook failed. :exc:`.NotFound` Invalid webhook ID. :exc:`.Forbidden` You do not have permission to fetch this webhook. Returns --------- :class:`.Webhook` The webhook you requested. """ data = await self.http.get_webhook(webhook_id) return Webhook.from_state(data, state=self._connection) async def fetch_sticker(self, sticker_id: int, /) -> Union[StandardSticker, GuildSticker]: """|coro| Retrieves a :class:`.Sticker` with the specified ID. .. versionadded:: 2.0 Raises -------- :exc:`.HTTPException` Retrieving the sticker failed. :exc:`.NotFound` Invalid sticker ID. Returns -------- Union[:class:`.StandardSticker`, :class:`.GuildSticker`] The sticker you requested. """ data = await self.http.get_sticker(sticker_id) cls, _ = _sticker_factory(data['type']) # type: ignore return cls(state=self._connection, data=data) # type: ignore async def fetch_premium_sticker_packs(self) -> List[StickerPack]: """|coro| Retrieves all available premium sticker packs. .. versionadded:: 2.0 Raises ------- :exc:`.HTTPException` Retrieving the sticker packs failed. Returns --------- List[:class:`.StickerPack`] All available premium sticker packs. """ data = await self.http.list_premium_sticker_packs() return [StickerPack(state=self._connection, data=pack) for pack in data['sticker_packs']] async def create_dm(self, user: Snowflake) -> DMChannel: """|coro| Creates a :class:`.DMChannel` with this user. This should be rarely called, as this is done transparently for most people. .. versionadded:: 2.0 Parameters ----------- user: :class:`~discord.abc.Snowflake` The user to create a DM with. Returns ------- :class:`.DMChannel` The channel that was created. """ state = self._connection found = state._get_private_channel_by_user(user.id) if found: return found data = await state.http.start_private_message(user.id) return state.add_dm_channel(data) def add_view(self, view: View, *, message_id: Optional[int] = None) -> None: """Registers a :class:`~discord.ui.View` for persistent listening. This method should be used for when a view is comprised of components that last longer than the lifecycle of the program. .. versionadded:: 2.0 Parameters ------------ view: :class:`discord.ui.View` The view to register for dispatching. message_id: Optional[:class:`int`] The message ID that the view is attached to. This is currently used to refresh the view's state during message update events. If not given then message update events are not propagated for the view. Raises ------- TypeError A view was not passed. ValueError The view is not persistent. A persistent view has no timeout and all their components have an explicitly provided custom_id. """ if not isinstance(view, View): raise TypeError(f'expected an instance of View not {view.__class__!r}') if not view.is_persistent(): raise ValueError('View is not persistent. Items need to have a custom_id set and View must have no timeout') self._connection.store_view(view, message_id) @property def persistent_views(self) -> Sequence[View]: """Sequence[:class:`.View`]: A sequence of persistent views added to the client. .. versionadded:: 2.0 """ return self._connection.persistent_views
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/client.py
client.py
from __future__ import annotations import struct from typing import TYPE_CHECKING, ClassVar, IO, Generator, Tuple, Optional from .errors import DiscordException __all__ = ( 'OggError', 'OggPage', 'OggStream', ) class OggError(DiscordException): """An exception that is thrown for Ogg stream parsing errors.""" pass # https://tools.ietf.org/html/rfc3533 # https://tools.ietf.org/html/rfc7845 class OggPage: _header: ClassVar[struct.Struct] = struct.Struct('<xBQIIIB') if TYPE_CHECKING: flag: int gran_pos: int serial: int pagenum: int crc: int segnum: int def __init__(self, stream: IO[bytes]) -> None: try: header = stream.read(struct.calcsize(self._header.format)) self.flag, self.gran_pos, self.serial, \ self.pagenum, self.crc, self.segnum = self._header.unpack(header) self.segtable: bytes = stream.read(self.segnum) bodylen = sum(struct.unpack('B'*self.segnum, self.segtable)) self.data: bytes = stream.read(bodylen) except Exception: raise OggError('bad data stream') from None def iter_packets(self) -> Generator[Tuple[bytes, bool], None, None]: packetlen = offset = 0 partial = True for seg in self.segtable: if seg == 255: packetlen += 255 partial = True else: packetlen += seg yield self.data[offset:offset+packetlen], True offset += packetlen packetlen = 0 partial = False if partial: yield self.data[offset:], False class OggStream: def __init__(self, stream: IO[bytes]) -> None: self.stream: IO[bytes] = stream def _next_page(self) -> Optional[OggPage]: head = self.stream.read(4) if head == b'OggS': return OggPage(self.stream) elif not head: return None else: raise OggError('invalid header magic') def _iter_pages(self) -> Generator[OggPage, None, None]: page = self._next_page() while page: yield page page = self._next_page() def iter_packets(self) -> Generator[bytes, None, None]: partial = b'' for page in self._iter_pages(): for data, complete in page.iter_packets(): partial += data if complete: yield partial partial = b''
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/oggparse.py
oggparse.py
from __future__ import annotations import datetime from typing import Any, Dict, Optional, TYPE_CHECKING, overload, Type, Tuple from .utils import _get_as_snowflake, parse_time, MISSING from .user import User from .errors import InvalidArgument from .enums import try_enum, ExpireBehaviour __all__ = ( 'IntegrationAccount', 'IntegrationApplication', 'Integration', 'StreamIntegration', 'BotIntegration', ) if TYPE_CHECKING: from .types.integration import ( IntegrationAccount as IntegrationAccountPayload, Integration as IntegrationPayload, StreamIntegration as StreamIntegrationPayload, BotIntegration as BotIntegrationPayload, IntegrationType, IntegrationApplication as IntegrationApplicationPayload, ) from .guild import Guild from .role import Role class IntegrationAccount: """Represents an integration account. .. versionadded:: 1.4 Attributes ----------- id: :class:`str` The account ID. name: :class:`str` The account name. """ __slots__ = ('id', 'name') def __init__(self, data: IntegrationAccountPayload) -> None: self.id: str = data['id'] self.name: str = data['name'] def __repr__(self) -> str: return f'<IntegrationAccount id={self.id} name={self.name!r}>' class Integration: """Represents a guild integration. .. versionadded:: 1.4 Attributes ----------- id: :class:`int` The integration ID. name: :class:`str` The integration name. guild: :class:`Guild` The guild of the integration. type: :class:`str` The integration type (i.e. Twitch). enabled: :class:`bool` Whether the integration is currently enabled. account: :class:`IntegrationAccount` The account linked to this integration. user: :class:`User` The user that added this integration. """ __slots__ = ( 'guild', 'id', '_state', 'type', 'name', 'account', 'user', 'enabled', ) def __init__(self, *, data: IntegrationPayload, guild: Guild) -> None: self.guild = guild self._state = guild._state self._from_data(data) def __repr__(self): return f"<{self.__class__.__name__} id={self.id} name={self.name!r}>" def _from_data(self, data: IntegrationPayload) -> None: self.id: int = int(data['id']) self.type: IntegrationType = data['type'] self.name: str = data['name'] self.account: IntegrationAccount = IntegrationAccount(data['account']) user = data.get('user') self.user = User(state=self._state, data=user) if user else None self.enabled: bool = data['enabled'] async def delete(self, *, reason: Optional[str] = None) -> None: """|coro| Deletes the integration. You must have the :attr:`~Permissions.manage_guild` permission to do this. Parameters ----------- reason: :class:`str` The reason the integration was deleted. Shows up on the audit log. .. versionadded:: 2.0 Raises ------- Forbidden You do not have permission to delete the integration. HTTPException Deleting the integration failed. """ await self._state.http.delete_integration(self.guild.id, self.id, reason=reason) class StreamIntegration(Integration): """Represents a stream integration for Twitch or YouTube. .. versionadded:: 2.0 Attributes ---------- id: :class:`int` The integration ID. name: :class:`str` The integration name. guild: :class:`Guild` The guild of the integration. type: :class:`str` The integration type (i.e. Twitch). enabled: :class:`bool` Whether the integration is currently enabled. syncing: :class:`bool` Where the integration is currently syncing. enable_emoticons: Optional[:class:`bool`] Whether emoticons should be synced for this integration (currently twitch only). expire_behaviour: :class:`ExpireBehaviour` The behaviour of expiring subscribers. Aliased to ``expire_behavior`` as well. expire_grace_period: :class:`int` The grace period (in days) for expiring subscribers. user: :class:`User` The user for the integration. account: :class:`IntegrationAccount` The integration account information. synced_at: :class:`datetime.datetime` An aware UTC datetime representing when the integration was last synced. """ __slots__ = ( 'revoked', 'expire_behaviour', 'expire_grace_period', 'synced_at', '_role_id', 'syncing', 'enable_emoticons', 'subscriber_count', ) def _from_data(self, data: StreamIntegrationPayload) -> None: super()._from_data(data) self.revoked: bool = data['revoked'] self.expire_behaviour: ExpireBehaviour = try_enum(ExpireBehaviour, data['expire_behavior']) self.expire_grace_period: int = data['expire_grace_period'] self.synced_at: datetime.datetime = parse_time(data['synced_at']) self._role_id: Optional[int] = _get_as_snowflake(data, 'role_id') self.syncing: bool = data['syncing'] self.enable_emoticons: bool = data['enable_emoticons'] self.subscriber_count: int = data['subscriber_count'] @property def expire_behavior(self) -> ExpireBehaviour: """:class:`ExpireBehaviour`: An alias for :attr:`expire_behaviour`.""" return self.expire_behaviour @property def role(self) -> Optional[Role]: """Optional[:class:`Role`] The role which the integration uses for subscribers.""" return self.guild.get_role(self._role_id) # type: ignore async def edit( self, *, expire_behaviour: ExpireBehaviour = MISSING, expire_grace_period: int = MISSING, enable_emoticons: bool = MISSING, ) -> None: """|coro| Edits the integration. You must have the :attr:`~Permissions.manage_guild` permission to do this. Parameters ----------- expire_behaviour: :class:`ExpireBehaviour` The behaviour when an integration subscription lapses. Aliased to ``expire_behavior`` as well. expire_grace_period: :class:`int` The period (in days) where the integration will ignore lapsed subscriptions. enable_emoticons: :class:`bool` Where emoticons should be synced for this integration (currently twitch only). Raises ------- Forbidden You do not have permission to edit the integration. HTTPException Editing the guild failed. InvalidArgument ``expire_behaviour`` did not receive a :class:`ExpireBehaviour`. """ payload: Dict[str, Any] = {} if expire_behaviour is not MISSING: if not isinstance(expire_behaviour, ExpireBehaviour): raise InvalidArgument('expire_behaviour field must be of type ExpireBehaviour') payload['expire_behavior'] = expire_behaviour.value if expire_grace_period is not MISSING: payload['expire_grace_period'] = expire_grace_period if enable_emoticons is not MISSING: payload['enable_emoticons'] = enable_emoticons # This endpoint is undocumented. # Unsure if it returns the data or not as a result await self._state.http.edit_integration(self.guild.id, self.id, **payload) async def sync(self) -> None: """|coro| Syncs the integration. You must have the :attr:`~Permissions.manage_guild` permission to do this. Raises ------- Forbidden You do not have permission to sync the integration. HTTPException Syncing the integration failed. """ await self._state.http.sync_integration(self.guild.id, self.id) self.synced_at = datetime.datetime.now(datetime.timezone.utc) class IntegrationApplication: """Represents an application for a bot integration. .. versionadded:: 2.0 Attributes ---------- id: :class:`int` The ID for this application. name: :class:`str` The application's name. icon: Optional[:class:`str`] The application's icon hash. description: :class:`str` The application's description. Can be an empty string. summary: :class:`str` The summary of the application. Can be an empty string. user: Optional[:class:`User`] The bot user on this application. """ __slots__ = ( 'id', 'name', 'icon', 'description', 'summary', 'user', ) def __init__(self, *, data: IntegrationApplicationPayload, state): self.id: int = int(data['id']) self.name: str = data['name'] self.icon: Optional[str] = data['icon'] self.description: str = data['description'] self.summary: str = data['summary'] user = data.get('bot') self.user: Optional[User] = User(state=state, data=user) if user else None class BotIntegration(Integration): """Represents a bot integration on discord. .. versionadded:: 2.0 Attributes ---------- id: :class:`int` The integration ID. name: :class:`str` The integration name. guild: :class:`Guild` The guild of the integration. type: :class:`str` The integration type (i.e. Twitch). enabled: :class:`bool` Whether the integration is currently enabled. user: :class:`User` The user that added this integration. account: :class:`IntegrationAccount` The integration account information. application: :class:`IntegrationApplication` The application tied to this integration. """ __slots__ = ('application',) def _from_data(self, data: BotIntegrationPayload) -> None: super()._from_data(data) self.application = IntegrationApplication(data=data['application'], state=self._state) def _integration_factory(value: str) -> Tuple[Type[Integration], str]: if value == 'discord': return BotIntegration, value elif value in ('twitch', 'youtube'): return StreamIntegration, value else: return Integration, value
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/integrations.py
integrations.py
from __future__ import annotations from typing import Any, Dict, List, Optional, TypeVar, Union, overload, TYPE_CHECKING from .permissions import Permissions from .errors import InvalidArgument from .colour import Colour from .mixins import Hashable from .utils import snowflake_time, _get_as_snowflake, MISSING __all__ = ( 'RoleTags', 'Role', ) if TYPE_CHECKING: import datetime from .types.role import ( Role as RolePayload, RoleTags as RoleTagPayload, ) from .types.guild import RolePositionUpdate from .guild import Guild from .member import Member from .state import ConnectionState class RoleTags: """Represents tags on a role. A role tag is a piece of extra information attached to a managed role that gives it context for the reason the role is managed. While this can be accessed, a useful interface is also provided in the :class:`Role` and :class:`Guild` classes as well. .. versionadded:: 1.6 Attributes ------------ bot_id: Optional[:class:`int`] The bot's user ID that manages this role. integration_id: Optional[:class:`int`] The integration ID that manages the role. """ __slots__ = ( 'bot_id', 'integration_id', '_premium_subscriber', ) def __init__(self, data: RoleTagPayload): self.bot_id: Optional[int] = _get_as_snowflake(data, 'bot_id') self.integration_id: Optional[int] = _get_as_snowflake(data, 'integration_id') # NOTE: The API returns "null" for this if it's valid, which corresponds to None. # This is different from other fields where "null" means "not there". # So in this case, a value of None is the same as True. # Which means we would need a different sentinel. self._premium_subscriber: Optional[Any] = data.get('premium_subscriber', MISSING) def is_bot_managed(self) -> bool: """:class:`bool`: Whether the role is associated with a bot.""" return self.bot_id is not None def is_premium_subscriber(self) -> bool: """:class:`bool`: Whether the role is the premium subscriber, AKA "boost", role for the guild.""" return self._premium_subscriber is None def is_integration(self) -> bool: """:class:`bool`: Whether the role is managed by an integration.""" return self.integration_id is not None def __repr__(self) -> str: return ( f'<RoleTags bot_id={self.bot_id} integration_id={self.integration_id} ' f'premium_subscriber={self.is_premium_subscriber()}>' ) R = TypeVar('R', bound='Role') 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', '_state', ) def __init__(self, *, guild: Guild, state: ConnectionState, data: RolePayload): 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: R, other: R) -> 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: R, other: R) -> bool: r = Role.__lt__(other, self) if r is NotImplemented: return NotImplemented return not r def __gt__(self: R, other: R) -> bool: return Role.__lt__(other, self) def __ge__(self: R, other: R) -> bool: r = Role.__lt__(self, other) if r is NotImplemented: return NotImplemented return not r def _update(self, data: RolePayload): 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.tags: Optional[RoleTags] try: self.tags = RoleTags(data['tags']) except KeyError: self.tags = None 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) @property def permissions(self) -> Permissions: """:class:`Permissions`: Returns the role's permissions.""" return Permissions(self._permissions) @property def colour(self) -> Colour: """:class:`Colour`: Returns the role colour. An alias exists under ``color``.""" return Colour(self._colour) @property def color(self) -> Colour: """:class:`Colour`: Returns the role color. An alias exists under ``colour``.""" return self.colour @property def created_at(self) -> datetime.datetime: """:class:`datetime.datetime`: Returns the role's creation time in UTC.""" return snowflake_time(self.id) @property def mention(self) -> str: """:class:`str`: Returns a string that allows you to mention a role.""" return f'<@&{self.id}>' @property 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)] 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, ) -> 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. 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. 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 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)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/role.py
role.py
from __future__ import annotations import copy import unicodedata from typing import ( Any, ClassVar, Dict, List, NamedTuple, Sequence, Set, Literal, Optional, TYPE_CHECKING, Tuple, Union, overload, ) from . import utils, abc from .role import Role from .member import Member, VoiceState from .emoji import Emoji from .errors import InvalidData from .permissions import PermissionOverwrite from .colour import Colour from .errors import InvalidArgument, ClientException from .channel import * from .channel import _guild_channel_factory from .channel import _threaded_guild_channel_factory from .enums import ( AuditLogAction, VideoQualityMode, VoiceRegion, ChannelType, try_enum, VerificationLevel, ContentFilter, NotificationLevel, NSFWLevel, ) from .mixins import Hashable from .user import User from .invite import Invite from .iterators import AuditLogIterator, MemberIterator from .widget import Widget from .asset import Asset from .flags import SystemChannelFlags from .integrations import Integration, _integration_factory from .stage_instance import StageInstance from .threads import Thread, ThreadMember from .sticker import GuildSticker from .file import File __all__ = ( 'Guild', ) MISSING = utils.MISSING if TYPE_CHECKING: from .abc import Snowflake, SnowflakeTime from .types.guild import Ban as BanPayload, Guild as GuildPayload, MFALevel, GuildFeature from .types.threads import ( Thread as ThreadPayload, ) from .types.voice import GuildVoiceState from .permissions import Permissions from .channel import VoiceChannel, StageChannel, TextChannel, CategoryChannel, StoreChannel from .template import Template from .webhook import Webhook from .state import ConnectionState from .voice_client import VoiceProtocol import datetime VocalGuildChannel = Union[VoiceChannel, StageChannel] GuildChannel = Union[VoiceChannel, StageChannel, TextChannel, CategoryChannel, StoreChannel] ByCategoryItem = Tuple[Optional[CategoryChannel], List[GuildChannel]] class BanEntry(NamedTuple): reason: Optional[str] user: User class _GuildLimit(NamedTuple): emoji: int stickers: int bitrate: float filesize: int 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_ICON``: Guild can upload an animated icon. - ``BANNER``: Guild can upload and use a banner. (i.e. :attr:`.banner`) - ``COMMERCE``: Guild can sell things using store channels. - ``COMMUNITY``: Guild is a community server. - ``DISCOVERABLE``: Guild shows up in Server Discovery. - ``FEATURABLE``: Guild is able to be featured in Server Discovery. - ``INVITE_SPLASH``: Guild's invite page can have a special splash. - ``MEMBER_VERIFICATION_GATE_ENABLED``: Guild has Membership Screening enabled. - ``MONETIZATION_ENABLED``: Guild has enabled monetization. - ``MORE_EMOJI``: Guild has increased custom emoji slots. - ``MORE_STICKERS``: Guild has increased custom sticker slots. - ``NEWS``: Guild can create news channels. - ``PARTNERED``: Guild is a partnered server. - ``PREVIEW_ENABLED``: Guild can be viewed before being accepted via Membership Screening. - ``PRIVATE_THREADS``: Guild has access to create private threads. - ``SEVEN_DAY_THREAD_ARCHIVE``: Guild has access to the seven day archive time for threads. - ``THREE_DAY_THREAD_ARCHIVE``: Guild has access to the three day archive time for threads. - ``TICKETED_EVENTS_ENABLED``: Guild has enabled ticketed events. - ``VANITY_URL``: Guild can have a vanity invite URL (e.g. discord.gg/discord-api). - ``VERIFIED``: Guild is a verified server. - ``VIP_REGIONS``: Guild has VIP voice regions. - ``WELCOME_SCREEN_ENABLED``: Guild has enabled the welcome screen. premium_tier: :class:`int` The premium tier for this guild. Corresponds to "Nitro Server" 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 """ __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', '_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', ) _PREMIUM_GUILD_LIMITS: ClassVar[Dict[Optional[int], _GuildLimit]] = { None: _GuildLimit(emoji=50, stickers=0, bitrate=96e3, filesize=8388608), 0: _GuildLimit(emoji=50, stickers=0, bitrate=96e3, filesize=8388608), 1: _GuildLimit(emoji=100, stickers=15, bitrate=128e3, filesize=8388608), 2: _GuildLimit(emoji=150, stickers=30, bitrate=256e3, filesize=52428800), 3: _GuildLimit(emoji=250, stickers=60, bitrate=384e3, filesize=104857600), } def __init__(self, *, data: GuildPayload, state: ConnectionState): self._channels: Dict[int, GuildChannel] = {} self._members: Dict[int, Member] = {} self._voice_states: Dict[int, VoiceState] = {} self._threads: Dict[int, Thread] = {} 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 __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) except KeyError: # if we're here then we're getting added into the cache after = VoiceState(data=data, channel=channel) before = VoiceState(data=data, channel=None) 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(map(lambda d: state.store_emoji(self, d), guild.get('emojis', []))) self.stickers: Tuple[GuildSticker, ...] = tuple( map(lambda d: state.store_sticker(self, d), 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.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._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) 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'])) # TODO: refactor/remove? def _sync(self, data: GuildPayload) -> None: try: self._large = data['large'] except KeyError: pass empty_tuple = 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, ch_type = _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)) @property def channels(self) -> List[GuildChannel]: """List[:class:`abc.GuildChannel`]: A list of channels that belongs to this guild.""" return list(self._channels.values()) @property 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()) @property 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 @property def voice_channels(self) -> List[VoiceChannel]: """List[:class:`VoiceChannel`]: A list of voice channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, VoiceChannel)] r.sort(key=lambda c: (c.position, c.id)) return r @property def stage_channels(self) -> List[StageChannel]: """List[:class:`StageChannel`]: A list of stage channels that belongs 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 @property 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 # The self member is *always* cached return self.get_member(self_id) # type: ignore @property 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) @property def text_channels(self) -> List[TextChannel]: """List[:class:`TextChannel`]: A list of text channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, TextChannel)] r.sort(key=lambda c: (c.position, c.id)) return r @property def categories(self) -> List[CategoryChannel]: """List[:class:`CategoryChannel`]: A list of categories that belongs 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 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 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) @property 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 @property def system_channel_flags(self) -> SystemChannelFlags: """:class:`SystemChannelFlags`: Returns the guild's system channel settings.""" return SystemChannelFlags._from_value(self._system_channel_flags) @property 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 @property 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 @property 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) @property 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 0 return max(more_stickers, self._PREMIUM_GUILD_LIMITS[self.premium_tier].stickers) @property 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) @property 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 @property def members(self) -> List[Member]: """List[:class:`Member`]: A list of members that belong to this guild.""" return list(self._members.values()) 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) @property 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] @property 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) @property 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 @property 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 @property 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 @property 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) @property def owner(self) -> Optional[Member]: """Optional[:class:`Member`]: The member that owns the guild.""" return self.get_member(self.owner_id) # type: ignore @property 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) @property 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') @property 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') @property 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') @property def member_count(self) -> int: """:class:`int`: Returns the true member count regardless of it being loaded fully or not. .. warning:: Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires :attr:`Intents.members` to be specified. """ return self._member_count @property 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) @property 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 @property 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 m.nick == name or m.name == 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, ) -> 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: discord.PermissionOverwrite(read_messages=False), guild.me: discord.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 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) # 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) # 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, 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. 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 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) # 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) # 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[bytes] = MISSING, banner: Optional[bytes] = MISSING, splash: Optional[bytes] = MISSING, discovery_splash: Optional[bytes] = 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, ) -> 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. 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: :class:`bytes` A :term:`py:bytes-like object` 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: :class:`bytes` A :term:`py:bytes-like object` representing the banner. Could be ``None`` to denote removal of the banner. This is only available to guilds that contain ``BANNER`` in :attr:`Guild.features`. splash: :class:`bytes` A :term:`py:bytes-like object` representing the invite splash. Only PNG/JPEG supported. Could be ``None`` to denote removing the splash. This is only available to guilds that contain ``INVITE_SPLASH`` in :attr:`Guild.features`. discovery_splash: :class:`bytes` A :term:`py:bytes-like object` representing the discovery splash. Only PNG/JPEG supported. Could be ``None`` to denote removing the splash. This is only available to guilds that contain ``DISCOVERABLE`` in :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. 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: if icon is None: fields['icon'] = icon else: fields['icon'] = utils._bytes_to_base64_data(icon) if banner is not MISSING: if banner is None: fields['banner'] = banner else: fields['banner'] = utils._bytes_to_base64_data(banner) if splash is not MISSING: if splash is None: fields['splash'] = splash else: fields['splash'] = utils._bytes_to_base64_data(splash) if discovery_splash is not MISSING: if discovery_splash is None: fields['discovery_splash'] = discovery_splash else: fields['discovery_splash'] = utils._bytes_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 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 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, ch_type = _guild_channel_factory(d['type']) if factory is None: raise InvalidData('Unknown channel type {type} for channel ID {id}.'.format_map(d)) channel = factory(guild=self, state=self._state, data=d) return channel 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: 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') 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 async def bans(self) -> List[BanEntry]: """|coro| Retrieves all the users that are banned from the guild as a :class:`list` of :class:`BanEntry`. You must have the :attr:`~Permissions.ban_members` permission to get this information. Raises ------- Forbidden You do not have proper permissions to get the information. HTTPException An error occurred while fetching the information. Returns -------- List[:class:`BanEntry`] A list of :class:`BanEntry` objects. """ data: List[BanPayload] = await self._state.http.get_bans(self.id) return [BanEntry(user=User(state=self._state, data=e['user']), reason=e['reason']) for e in data] 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.') if roles: role_ids = [str(role.id) for role in roles] else: role_ids = [] 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) -> 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.') if roles: role_ids = [str(role.id) for role in roles] else: role_ids = [] 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. """ 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 = {'name': name} 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: str, 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']) if factory is None: raise InvalidData('Unknown integration type {type!r} for integration ID {id}'.format_map(d)) 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. """ payload = { 'name': name, } if description: payload['description'] = description try: emoji = unicodedata.name(emoji) except TypeError: pass else: emoji = emoji.replace(' ', '_') payload['tags'] = emoji data = await self._state.http.create_guild_sticker(self.id, payload, file, 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: bytes, 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. Parameters ----------- name: :class:`str` The emoji name. Must be at least 2 characters. image: :class:`bytes` The :term:`py:bytes-like object` 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 = utils._bytes_to_base64_data(image) if roles: role_ids = [role.id for role in roles] else: role_ids = [] data = await self._state.http.create_custom_emoji(self.id, name, img, 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) -> 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. .. versionadded:: 1.3 Raises ------- HTTPException Retrieving the roles failed. Returns ------- List[:class:`Role`] All roles in the guild. """ data = await self._state.http.get_roles(self.id) return [Role(guild=self, state=self._state, data=d) for d in data] @overload async def create_role( self, *, reason: Optional[str] = ..., name: str = ..., permissions: Permissions = ..., colour: Union[Colour, int] = ..., hoist: bool = ..., mentionable: bool = ..., ) -> Role: ... @overload async def create_role( self, *, reason: Optional[str] = ..., name: str = ..., permissions: Permissions = ..., color: Union[Colour, int] = ..., hoist: bool = ..., mentionable: bool = ..., ) -> 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, 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. 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``. 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 data = await self._state.http.create_role(self.id, reason=reason, **fields) role = Role(guild=self, data=data, state=self._state) # TODO: add to cache return role 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[Dict[str, Any]] = [] for role, position in positions.items(): payload = {'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_days: Literal[0, 1, 2, 3, 4, 5, 6, 7] = 1, ) -> 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. Parameters ----------- user: :class:`abc.Snowflake` The user to ban from their guild. delete_message_days: :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. reason: Optional[:class:`str`] The reason the user got banned. Raises ------- Forbidden You do not have the proper permissions to ban. HTTPException Banning failed. """ await self._state.http.ban(user.id, self.id, delete_message_days, 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: int = 100, before: Optional[SnowflakeTime] = None, after: Optional[SnowflakeTime] = None, oldest_first: Optional[bool] = None, user: Snowflake = None, action: 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=discord.AuditLogAction.ban): print(f'{entry.user} banned {entry.target}') Getting entries made by a specific user: :: entries = await guild.audit_logs(limit=None, user=guild.me).flatten() await channel.send(f'I made {len(entries)} moderation actions.') Parameters ----------- limit: Optional[:class:`int`] The number of entries to retrieve. If ``None`` retrieve all entries. before: 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: 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: :class:`bool` If set to ``True``, return entries in oldest->newest order. Defaults to ``True`` if ``after`` is specified, otherwise ``False``. user: :class:`abc.Snowflake` The moderator to filter entries from. action: :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. """ if user is not None: user_id = user.id else: user_id = None if action: action = action.value 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:`~discord.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) -> None: """|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. """ if not self._state._intents.members: raise ClientException('Intents.members must be enabled to use this.') if not self._state.is_guild_evicted(self): return await self._state.chunk_guild(self, cache=cache) 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 query is None: 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 ): """|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)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/guild.py
guild.py
from __future__ import annotations from typing import Dict, List, Optional, TYPE_CHECKING, Any, Tuple, Union if TYPE_CHECKING: from aiohttp import ClientResponse, ClientWebSocketResponse try: from requests import Response _ResponseType = Union[ClientResponse, Response] except ModuleNotFoundError: _ResponseType = ClientResponse from .interactions import Interaction __all__ = ( 'DiscordException', 'ClientException', 'NoMoreItems', 'GatewayNotFound', 'HTTPException', 'Forbidden', 'NotFound', 'DiscordServerError', 'InvalidData', 'InvalidArgument', 'LoginFailure', 'ConnectionClosed', 'PrivilegedIntentsRequired', 'InteractionResponded', ) class DiscordException(Exception): """Base exception class for discord.py Ideally speaking, this could be caught to handle any exceptions raised from this library. """ pass class ClientException(DiscordException): """Exception that's raised when an operation in the :class:`Client` fails. These are usually for exceptions that happened due to user input. """ pass class NoMoreItems(DiscordException): """Exception that is raised when an async iteration operation has no more items.""" pass class GatewayNotFound(DiscordException): """An exception that is raised when the gateway for Discord could not be found""" def __init__(self): message = 'The gateway to connect to discord was not found.' super().__init__(message) 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) class HTTPException(DiscordException): """Exception that's raised when an HTTP request operation fails. Attributes ------------ response: :class:`aiohttp.ClientResponse` The response of the failed HTTP request. This is an instance of :class:`aiohttp.ClientResponse`. In some cases this could also be a :class:`requests.Response`. text: :class:`str` The text of the error. Could be an empty string. status: :class:`int` The status code of the HTTP request. code: :class:`int` The Discord specific error code for the failure. """ def __init__(self, response: _ResponseType, message: Optional[Union[str, Dict[str, Any]]]): self.response: _ResponseType = response self.status: int = response.status # type: ignore self.code: int self.text: str if isinstance(message, dict): self.code = message.get('code', 0) base = message.get('message', '') errors = message.get('errors') if errors: errors = _flatten_error_dict(errors) helpful = '\n'.join('In %s: %s' % t for t in errors.items()) self.text = base + '\n' + helpful else: self.text = base else: self.text = message or '' self.code = 0 fmt = '{0.status} {0.reason} (error code: {1})' if len(self.text): fmt += ': {2}' super().__init__(fmt.format(self.response, self.code, self.text)) class Forbidden(HTTPException): """Exception that's raised for when status code 403 occurs. Subclass of :exc:`HTTPException` """ pass class NotFound(HTTPException): """Exception that's raised for when status code 404 occurs. Subclass of :exc:`HTTPException` """ pass class DiscordServerError(HTTPException): """Exception that's raised for when a 500 range status code occurs. Subclass of :exc:`HTTPException`. .. versionadded:: 1.5 """ pass class InvalidData(ClientException): """Exception that's raised when the library encounters unknown or invalid data from Discord. """ pass 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`. """ pass class LoginFailure(ClientException): """Exception that's raised when the :meth:`Client.login` function fails to log you in from improper credentials or some other misc. failure. """ pass class ConnectionClosed(ClientException): """Exception that's raised when the gateway connection is closed for reasons that could not be handled internally. Attributes ----------- code: :class:`int` The close code of the websocket. reason: :class:`str` The reason provided for the closure. shard_id: Optional[:class:`int`] The shard ID that got closed if applicable. """ def __init__(self, socket: ClientWebSocketResponse, *, shard_id: Optional[int], code: Optional[int] = None): # This exception is just the same exception except # reconfigured to subclass ClientException for users self.code: int = code or socket.close_code or -1 # aiohttp doesn't seem to consistently provide close reason self.reason: str = '' self.shard_id: Optional[int] = shard_id super().__init__(f'Shard ID {self.shard_id} WebSocket closed with {self.code}') class PrivilegedIntentsRequired(ClientException): """Exception that's raised when the gateway is requesting privileged intents but they're not ticked in the developer page yet. Go to https://discord.com/developers/applications/ and enable the intents that are required. Currently these are as follows: - :attr:`Intents.members` - :attr:`Intents.presences` Attributes ----------- shard_id: Optional[:class:`int`] The shard ID that got closed if applicable. """ def __init__(self, shard_id: Optional[int]): self.shard_id: Optional[int] = shard_id msg = ( 'Shard ID %s is requesting privileged intents that have not been explicitly enabled in the ' 'developer portal. It is recommended to go to https://discord.com/developers/applications/ ' 'and explicitly enable the privileged intents within your application\'s page. If this is not ' 'possible, then consider disabling the privileged intents instead.' ) super().__init__(msg % shard_id) class InteractionResponded(ClientException): """Exception that's raised when sending another interaction response using :class:`InteractionResponse` when one has already been done before. An interaction can only respond once. .. versionadded:: 2.0 Attributes ----------- interaction: :class:`Interaction` The interaction that's already been responded to. """ def __init__(self, interaction: Interaction): self.interaction: Interaction = interaction super().__init__('This interaction has already been responded to before')
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/errors.py
errors.py
import types from collections import namedtuple from typing import Any, ClassVar, Dict, List, Optional, TYPE_CHECKING, Type, TypeVar __all__ = ( 'Enum', 'ChannelType', 'MessageType', 'VoiceRegion', 'SpeakingState', 'VerificationLevel', 'ContentFilter', 'Status', 'DefaultAvatar', 'AuditLogAction', 'AuditLogActionCategory', 'UserFlags', 'ActivityType', 'NotificationLevel', 'TeamMembershipState', 'WebhookType', 'ExpireBehaviour', 'ExpireBehavior', 'StickerType', 'StickerFormatType', 'InviteTarget', 'VideoQualityMode', 'ComponentType', 'ButtonStyle', 'StagePrivacyLevel', 'InteractionType', 'InteractionResponseType', 'NSFWLevel', ) def _create_value_cls(name, comparable): cls = namedtuple('_EnumValue_' + name, 'name value') cls.__repr__ = lambda self: f'<{name}.{self.name}: {self.value!r}>' cls.__str__ = lambda self: f'{name}.{self.name}' if comparable: cls.__le__ = lambda self, other: isinstance(other, self.__class__) and self.value <= other.value cls.__ge__ = lambda self, other: isinstance(other, self.__class__) and self.value >= other.value cls.__lt__ = lambda self, other: isinstance(other, self.__class__) and self.value < other.value cls.__gt__ = lambda self, other: isinstance(other, self.__class__) and self.value > other.value return cls def _is_descriptor(obj): return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__') class EnumMeta(type): if TYPE_CHECKING: __name__: ClassVar[str] _enum_member_names_: ClassVar[List[str]] _enum_member_map_: ClassVar[Dict[str, Any]] _enum_value_map_: ClassVar[Dict[Any, Any]] def __new__(cls, name, bases, attrs, *, comparable: bool = False): value_mapping = {} member_mapping = {} member_names = [] value_cls = _create_value_cls(name, comparable) for key, value in list(attrs.items()): is_descriptor = _is_descriptor(value) if key[0] == '_' and not is_descriptor: continue # Special case classmethod to just pass through if isinstance(value, classmethod): continue if is_descriptor: setattr(value_cls, key, value) del attrs[key] continue try: new_value = value_mapping[value] except KeyError: new_value = value_cls(name=key, value=value) value_mapping[value] = new_value member_names.append(key) member_mapping[key] = new_value attrs[key] = new_value attrs['_enum_value_map_'] = value_mapping attrs['_enum_member_map_'] = member_mapping attrs['_enum_member_names_'] = member_names attrs['_enum_value_cls_'] = value_cls actual_cls = super().__new__(cls, name, bases, attrs) value_cls._actual_enum_cls_ = actual_cls # type: ignore return actual_cls def __iter__(cls): return (cls._enum_member_map_[name] for name in cls._enum_member_names_) def __reversed__(cls): return (cls._enum_member_map_[name] for name in reversed(cls._enum_member_names_)) def __len__(cls): return len(cls._enum_member_names_) def __repr__(cls): return f'<enum {cls.__name__}>' @property def __members__(cls): return types.MappingProxyType(cls._enum_member_map_) def __call__(cls, value): try: return cls._enum_value_map_[value] except (KeyError, TypeError): raise ValueError(f"{value!r} is not a valid {cls.__name__}") def __getitem__(cls, key): return cls._enum_member_map_[key] def __setattr__(cls, name, value): raise TypeError('Enums are immutable.') def __delattr__(cls, attr): raise TypeError('Enums are immutable') def __instancecheck__(self, instance): # isinstance(x, Y) # -> __instancecheck__(Y, x) try: return instance._actual_enum_cls_ is self except AttributeError: return False if TYPE_CHECKING: from enum import Enum else: class Enum(metaclass=EnumMeta): @classmethod def try_value(cls, value): try: return cls._enum_value_map_[value] except (KeyError, TypeError): return value class ChannelType(Enum): text = 0 private = 1 voice = 2 group = 3 category = 4 news = 5 store = 6 news_thread = 10 public_thread = 11 private_thread = 12 stage_voice = 13 def __str__(self): return self.name class MessageType(Enum): default = 0 recipient_add = 1 recipient_remove = 2 call = 3 channel_name_change = 4 channel_icon_change = 5 pins_add = 6 new_member = 7 premium_guild_subscription = 8 premium_guild_tier_1 = 9 premium_guild_tier_2 = 10 premium_guild_tier_3 = 11 channel_follow_add = 12 guild_stream = 13 guild_discovery_disqualified = 14 guild_discovery_requalified = 15 guild_discovery_grace_period_initial_warning = 16 guild_discovery_grace_period_final_warning = 17 thread_created = 18 reply = 19 application_command = 20 thread_starter_message = 21 guild_invite_reminder = 22 class VoiceRegion(Enum): us_west = 'us-west' us_east = 'us-east' us_south = 'us-south' us_central = 'us-central' eu_west = 'eu-west' eu_central = 'eu-central' singapore = 'singapore' london = 'london' sydney = 'sydney' amsterdam = 'amsterdam' frankfurt = 'frankfurt' brazil = 'brazil' hongkong = 'hongkong' russia = 'russia' japan = 'japan' southafrica = 'southafrica' south_korea = 'south-korea' india = 'india' europe = 'europe' dubai = 'dubai' vip_us_east = 'vip-us-east' vip_us_west = 'vip-us-west' vip_amsterdam = 'vip-amsterdam' def __str__(self): return self.value class SpeakingState(Enum): none = 0 voice = 1 soundshare = 2 priority = 4 def __str__(self): return self.name def __int__(self): return self.value class VerificationLevel(Enum, comparable=True): none = 0 low = 1 medium = 2 high = 3 highest = 4 def __str__(self): return self.name class ContentFilter(Enum, comparable=True): disabled = 0 no_role = 1 all_members = 2 def __str__(self): return self.name class Status(Enum): online = 'online' offline = 'offline' idle = 'idle' dnd = 'dnd' do_not_disturb = 'dnd' invisible = 'invisible' def __str__(self): return self.value class DefaultAvatar(Enum): blurple = 0 grey = 1 gray = 1 green = 2 orange = 3 red = 4 def __str__(self): return self.name class NotificationLevel(Enum, comparable=True): all_messages = 0 only_mentions = 1 class AuditLogActionCategory(Enum): create = 1 delete = 2 update = 3 class AuditLogAction(Enum): # fmt: off guild_update = 1 channel_create = 10 channel_update = 11 channel_delete = 12 overwrite_create = 13 overwrite_update = 14 overwrite_delete = 15 kick = 20 member_prune = 21 ban = 22 unban = 23 member_update = 24 member_role_update = 25 member_move = 26 member_disconnect = 27 bot_add = 28 role_create = 30 role_update = 31 role_delete = 32 invite_create = 40 invite_update = 41 invite_delete = 42 webhook_create = 50 webhook_update = 51 webhook_delete = 52 emoji_create = 60 emoji_update = 61 emoji_delete = 62 message_delete = 72 message_bulk_delete = 73 message_pin = 74 message_unpin = 75 integration_create = 80 integration_update = 81 integration_delete = 82 stage_instance_create = 83 stage_instance_update = 84 stage_instance_delete = 85 sticker_create = 90 sticker_update = 91 sticker_delete = 92 thread_create = 110 thread_update = 111 thread_delete = 112 # fmt: on @property def category(self) -> Optional[AuditLogActionCategory]: # fmt: off lookup: Dict[AuditLogAction, Optional[AuditLogActionCategory]] = { AuditLogAction.guild_update: AuditLogActionCategory.update, AuditLogAction.channel_create: AuditLogActionCategory.create, AuditLogAction.channel_update: AuditLogActionCategory.update, AuditLogAction.channel_delete: AuditLogActionCategory.delete, AuditLogAction.overwrite_create: AuditLogActionCategory.create, AuditLogAction.overwrite_update: AuditLogActionCategory.update, AuditLogAction.overwrite_delete: AuditLogActionCategory.delete, AuditLogAction.kick: None, AuditLogAction.member_prune: None, AuditLogAction.ban: None, AuditLogAction.unban: None, AuditLogAction.member_update: AuditLogActionCategory.update, AuditLogAction.member_role_update: AuditLogActionCategory.update, AuditLogAction.member_move: None, AuditLogAction.member_disconnect: None, AuditLogAction.bot_add: None, AuditLogAction.role_create: AuditLogActionCategory.create, AuditLogAction.role_update: AuditLogActionCategory.update, AuditLogAction.role_delete: AuditLogActionCategory.delete, AuditLogAction.invite_create: AuditLogActionCategory.create, AuditLogAction.invite_update: AuditLogActionCategory.update, AuditLogAction.invite_delete: AuditLogActionCategory.delete, AuditLogAction.webhook_create: AuditLogActionCategory.create, AuditLogAction.webhook_update: AuditLogActionCategory.update, AuditLogAction.webhook_delete: AuditLogActionCategory.delete, AuditLogAction.emoji_create: AuditLogActionCategory.create, AuditLogAction.emoji_update: AuditLogActionCategory.update, AuditLogAction.emoji_delete: AuditLogActionCategory.delete, AuditLogAction.message_delete: AuditLogActionCategory.delete, AuditLogAction.message_bulk_delete: AuditLogActionCategory.delete, AuditLogAction.message_pin: None, AuditLogAction.message_unpin: None, AuditLogAction.integration_create: AuditLogActionCategory.create, AuditLogAction.integration_update: AuditLogActionCategory.update, AuditLogAction.integration_delete: AuditLogActionCategory.delete, AuditLogAction.stage_instance_create: AuditLogActionCategory.create, AuditLogAction.stage_instance_update: AuditLogActionCategory.update, AuditLogAction.stage_instance_delete: AuditLogActionCategory.delete, AuditLogAction.sticker_create: AuditLogActionCategory.create, AuditLogAction.sticker_update: AuditLogActionCategory.update, AuditLogAction.sticker_delete: AuditLogActionCategory.delete, AuditLogAction.thread_create: AuditLogActionCategory.create, AuditLogAction.thread_update: AuditLogActionCategory.update, AuditLogAction.thread_delete: AuditLogActionCategory.delete, } # fmt: on return lookup[self] @property def target_type(self) -> Optional[str]: v = self.value if v == -1: return 'all' elif v < 10: return 'guild' elif v < 20: return 'channel' elif v < 30: return 'user' elif v < 40: return 'role' elif v < 50: return 'invite' elif v < 60: return 'webhook' elif v < 70: return 'emoji' elif v == 73: return 'channel' elif v < 80: return 'message' elif v < 83: return 'integration' elif v < 90: return 'stage_instance' elif v < 93: return 'sticker' elif v < 113: return 'thread' class UserFlags(Enum): staff = 1 partner = 2 hypesquad = 4 bug_hunter = 8 mfa_sms = 16 premium_promo_dismissed = 32 hypesquad_bravery = 64 hypesquad_brilliance = 128 hypesquad_balance = 256 early_supporter = 512 team_user = 1024 system = 4096 has_unread_urgent_messages = 8192 bug_hunter_level_2 = 16384 verified_bot = 65536 verified_bot_developer = 131072 discord_certified_moderator = 262144 class ActivityType(Enum): unknown = -1 playing = 0 streaming = 1 listening = 2 watching = 3 custom = 4 competing = 5 def __int__(self): return self.value class TeamMembershipState(Enum): invited = 1 accepted = 2 class WebhookType(Enum): incoming = 1 channel_follower = 2 application = 3 class ExpireBehaviour(Enum): remove_role = 0 kick = 1 ExpireBehavior = ExpireBehaviour class StickerType(Enum): standard = 1 guild = 2 class StickerFormatType(Enum): png = 1 apng = 2 lottie = 3 @property def file_extension(self) -> str: # fmt: off lookup: Dict[StickerFormatType, str] = { StickerFormatType.png: 'png', StickerFormatType.apng: 'png', StickerFormatType.lottie: 'json', } # fmt: on return lookup[self] class InviteTarget(Enum): unknown = 0 stream = 1 embedded_application = 2 class InteractionType(Enum): ping = 1 application_command = 2 component = 3 class InteractionResponseType(Enum): pong = 1 # ack = 2 (deprecated) # channel_message = 3 (deprecated) channel_message = 4 # (with source) deferred_channel_message = 5 # (with source) deferred_message_update = 6 # for components message_update = 7 # for components class VideoQualityMode(Enum): auto = 1 full = 2 def __int__(self): return self.value class ComponentType(Enum): action_row = 1 button = 2 select = 3 def __int__(self): return self.value class ButtonStyle(Enum): primary = 1 secondary = 2 success = 3 danger = 4 link = 5 # Aliases blurple = 1 grey = 2 gray = 2 green = 3 red = 4 url = 5 def __int__(self): return self.value class StagePrivacyLevel(Enum): public = 1 closed = 2 guild_only = 2 class NSFWLevel(Enum, comparable=True): default = 0 explicit = 1 safe = 2 age_restricted = 3 T = TypeVar('T') def create_unknown_value(cls: Type[T], val: Any) -> T: value_cls = cls._enum_value_cls_ # type: ignore name = f'unknown_{val}' return value_cls(name=name, value=val) 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._enum_value_map_[val] # type: ignore except (KeyError, TypeError, AttributeError): return create_unknown_value(cls, val)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/enums.py
enums.py
from __future__ import annotations from typing import TYPE_CHECKING, Optional, Set, List if TYPE_CHECKING: from .types.raw_models import ( MessageDeleteEvent, BulkMessageDeleteEvent, ReactionActionEvent, MessageUpdateEvent, ReactionClearEvent, ReactionClearEmojiEvent, IntegrationDeleteEvent ) from .message import Message from .partial_emoji import PartialEmoji from .member import Member __all__ = ( 'RawMessageDeleteEvent', 'RawBulkMessageDeleteEvent', 'RawMessageUpdateEvent', 'RawReactionActionEvent', 'RawReactionClearEvent', 'RawReactionClearEmojiEvent', 'RawIntegrationDeleteEvent', ) class _RawReprMixin: def __repr__(self) -> str: value = ' '.join(f'{attr}={getattr(self, attr)!r}' for attr in self.__slots__) return f'<{self.__class__.__name__} {value}>' class RawMessageDeleteEvent(_RawReprMixin): """Represents the event payload for a :func:`on_raw_message_delete` event. Attributes ------------ channel_id: :class:`int` The channel ID where the deletion took place. guild_id: Optional[:class:`int`] The guild ID where the deletion took place, if applicable. message_id: :class:`int` The message ID that got deleted. cached_message: Optional[:class:`Message`] The cached message, if found in the internal message cache. """ __slots__ = ('message_id', 'channel_id', 'guild_id', 'cached_message') def __init__(self, data: MessageDeleteEvent) -> None: self.message_id: int = int(data['id']) self.channel_id: int = int(data['channel_id']) self.cached_message: Optional[Message] = None try: self.guild_id: Optional[int] = int(data['guild_id']) except KeyError: self.guild_id: Optional[int] = None class RawBulkMessageDeleteEvent(_RawReprMixin): """Represents the event payload for a :func:`on_raw_bulk_message_delete` event. Attributes ----------- message_ids: Set[:class:`int`] A :class:`set` of the message IDs that were deleted. channel_id: :class:`int` The channel ID where the message got deleted. guild_id: Optional[:class:`int`] The guild ID where the message got deleted, if applicable. cached_messages: List[:class:`Message`] The cached messages, if found in the internal message cache. """ __slots__ = ('message_ids', 'channel_id', 'guild_id', 'cached_messages') def __init__(self, data: BulkMessageDeleteEvent) -> None: self.message_ids: Set[int] = {int(x) for x in data.get('ids', [])} self.channel_id: int = int(data['channel_id']) self.cached_messages: List[Message] = [] try: self.guild_id: Optional[int] = int(data['guild_id']) except KeyError: self.guild_id: Optional[int] = None class RawMessageUpdateEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_message_edit` event. Attributes ----------- message_id: :class:`int` The message ID that got updated. channel_id: :class:`int` The channel ID where the update took place. .. versionadded:: 1.3 guild_id: Optional[:class:`int`] The guild ID where the message got updated, if applicable. .. versionadded:: 1.7 data: :class:`dict` The raw data given by the `gateway <https://discord.com/developers/docs/topics/gateway#message-update>`_ cached_message: Optional[:class:`Message`] The cached message, if found in the internal message cache. Represents the message before it is modified by the data in :attr:`RawMessageUpdateEvent.data`. """ __slots__ = ('message_id', 'channel_id', 'guild_id', 'data', 'cached_message') def __init__(self, data: MessageUpdateEvent) -> None: self.message_id: int = int(data['id']) self.channel_id: int = int(data['channel_id']) self.data: MessageUpdateEvent = data self.cached_message: Optional[Message] = None try: self.guild_id: Optional[int] = int(data['guild_id']) except KeyError: self.guild_id: Optional[int] = None class RawReactionActionEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_reaction_add` or :func:`on_raw_reaction_remove` event. Attributes ----------- message_id: :class:`int` The message ID that got or lost a reaction. user_id: :class:`int` The user ID who added the reaction or whose reaction was removed. channel_id: :class:`int` The channel ID where the reaction got added or removed. guild_id: Optional[:class:`int`] The guild ID where the reaction got added or removed, if applicable. emoji: :class:`PartialEmoji` The custom or unicode emoji being used. member: Optional[:class:`Member`] The member who added the reaction. Only available if `event_type` is `REACTION_ADD` and the reaction is inside a guild. .. versionadded:: 1.3 event_type: :class:`str` The event type that triggered this action. Can be ``REACTION_ADD`` for reaction addition or ``REACTION_REMOVE`` for reaction removal. .. versionadded:: 1.3 """ __slots__ = ('message_id', 'user_id', 'channel_id', 'guild_id', 'emoji', 'event_type', 'member') def __init__(self, data: ReactionActionEvent, emoji: PartialEmoji, event_type: str) -> None: self.message_id: int = int(data['message_id']) self.channel_id: int = int(data['channel_id']) self.user_id: int = int(data['user_id']) self.emoji: PartialEmoji = emoji self.event_type: str = event_type self.member: Optional[Member] = None try: self.guild_id: Optional[int] = int(data['guild_id']) except KeyError: self.guild_id: Optional[int] = None class RawReactionClearEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_reaction_clear` event. Attributes ----------- message_id: :class:`int` The message ID that got its reactions cleared. channel_id: :class:`int` The channel ID where the reactions got cleared. guild_id: Optional[:class:`int`] The guild ID where the reactions got cleared. """ __slots__ = ('message_id', 'channel_id', 'guild_id') def __init__(self, data: ReactionClearEvent) -> None: self.message_id: int = int(data['message_id']) self.channel_id: int = int(data['channel_id']) try: self.guild_id: Optional[int] = int(data['guild_id']) except KeyError: self.guild_id: Optional[int] = None class RawReactionClearEmojiEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_reaction_clear_emoji` event. .. versionadded:: 1.3 Attributes ----------- message_id: :class:`int` The message ID that got its reactions cleared. channel_id: :class:`int` The channel ID where the reactions got cleared. guild_id: Optional[:class:`int`] The guild ID where the reactions got cleared. emoji: :class:`PartialEmoji` The custom or unicode emoji being removed. """ __slots__ = ('message_id', 'channel_id', 'guild_id', 'emoji') def __init__(self, data: ReactionClearEmojiEvent, emoji: PartialEmoji) -> None: self.emoji: PartialEmoji = emoji self.message_id: int = int(data['message_id']) self.channel_id: int = int(data['channel_id']) try: self.guild_id: Optional[int] = int(data['guild_id']) except KeyError: self.guild_id: Optional[int] = None class RawIntegrationDeleteEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_integration_delete` event. .. versionadded:: 2.0 Attributes ----------- integration_id: :class:`int` The ID of the integration that got deleted. application_id: Optional[:class:`int`] The ID of the bot/OAuth2 application for this deleted integration. guild_id: :class:`int` The guild ID where the integration got deleted. """ __slots__ = ('integration_id', 'application_id', 'guild_id') def __init__(self, data: IntegrationDeleteEvent) -> None: self.integration_id: int = int(data['id']) self.guild_id: int = int(data['guild_id']) try: self.application_id: Optional[int] = int(data['application_id']) except KeyError: self.application_id: Optional[int] = None
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/raw_models.py
raw_models.py
from __future__ import annotations import array import asyncio import collections.abc from typing import ( Any, AsyncIterator, Callable, Dict, ForwardRef, Generic, Iterable, Iterator, List, Literal, Mapping, Optional, Protocol, Sequence, Tuple, Type, TypeVar, Union, overload, TYPE_CHECKING, ) import unicodedata from base64 import b64encode from bisect import bisect_left import datetime import functools from inspect import isawaitable as _isawaitable, signature as _signature from operator import attrgetter import json import re import sys import types import warnings from .errors import InvalidArgument try: import orjson except ModuleNotFoundError: HAS_ORJSON = False else: HAS_ORJSON = True __all__ = ( 'oauth_url', 'snowflake_time', 'time_snowflake', 'find', 'get', 'sleep_until', 'utcnow', 'remove_markdown', 'escape_markdown', 'escape_mentions', 'as_chunks', 'format_dt', ) DISCORD_EPOCH = 1420070400000 class _MissingSentinel: def __eq__(self, other): return False def __bool__(self): return False def __repr__(self): return '...' MISSING: Any = _MissingSentinel() class _cached_property: def __init__(self, function): self.function = function self.__doc__ = getattr(function, '__doc__') def __get__(self, instance, owner): if instance is None: return self value = self.function(instance) setattr(instance, self.function.__name__, value) return value if TYPE_CHECKING: from functools import cached_property as cached_property from typing_extensions import ParamSpec from .permissions import Permissions from .abc import Snowflake from .invite import Invite from .template import Template class _RequestLike(Protocol): headers: Mapping[str, Any] P = ParamSpec('P') else: cached_property = _cached_property T = TypeVar('T') T_co = TypeVar('T_co', covariant=True) _Iter = Union[Iterator[T], AsyncIterator[T]] class CachedSlotProperty(Generic[T, T_co]): def __init__(self, name: str, function: Callable[[T], T_co]) -> None: self.name = name self.function = function self.__doc__ = getattr(function, '__doc__') @overload def __get__(self, instance: None, owner: Type[T]) -> CachedSlotProperty[T, T_co]: ... @overload def __get__(self, instance: T, owner: Type[T]) -> T_co: ... def __get__(self, instance: Optional[T], owner: Type[T]) -> Any: if instance is None: return self try: return getattr(instance, self.name) except AttributeError: value = self.function(instance) setattr(instance, self.name, value) return value class classproperty(Generic[T_co]): def __init__(self, fget: Callable[[Any], T_co]) -> None: self.fget = fget def __get__(self, instance: Optional[Any], owner: Type[Any]) -> T_co: return self.fget(owner) def __set__(self, instance, value) -> None: raise AttributeError('cannot set attribute') def cached_slot_property(name: str) -> Callable[[Callable[[T], T_co]], CachedSlotProperty[T, T_co]]: def decorator(func: Callable[[T], T_co]) -> CachedSlotProperty[T, T_co]: return CachedSlotProperty(name, func) return decorator class SequenceProxy(Generic[T_co], collections.abc.Sequence): """Read-only proxy of a Sequence.""" def __init__(self, proxied: Sequence[T_co]): self.__proxied = proxied def __getitem__(self, idx: int) -> T_co: return self.__proxied[idx] def __len__(self) -> int: return len(self.__proxied) def __contains__(self, item: Any) -> bool: return item in self.__proxied def __iter__(self) -> Iterator[T_co]: return iter(self.__proxied) def __reversed__(self) -> Iterator[T_co]: return reversed(self.__proxied) def index(self, value: Any, *args, **kwargs) -> int: return self.__proxied.index(value, *args, **kwargs) def count(self, value: Any) -> int: return self.__proxied.count(value) @overload def parse_time(timestamp: None) -> None: ... @overload def parse_time(timestamp: str) -> datetime.datetime: ... @overload def parse_time(timestamp: Optional[str]) -> Optional[datetime.datetime]: ... def parse_time(timestamp: Optional[str]) -> Optional[datetime.datetime]: if timestamp: return datetime.datetime.fromisoformat(timestamp) return None def copy_doc(original: Callable) -> Callable[[T], T]: def decorator(overriden: T) -> T: overriden.__doc__ = original.__doc__ overriden.__signature__ = _signature(original) # type: ignore return overriden return decorator def deprecated(instead: Optional[str] = None) -> Callable[[Callable[P, T]], Callable[P, T]]: def actual_decorator(func: Callable[P, T]) -> Callable[P, T]: @functools.wraps(func) def decorated(*args: P.args, **kwargs: P.kwargs) -> T: warnings.simplefilter('always', DeprecationWarning) # turn off filter if instead: fmt = "{0.__name__} is deprecated, use {1} instead." else: fmt = '{0.__name__} is deprecated.' warnings.warn(fmt.format(func, instead), stacklevel=3, category=DeprecationWarning) warnings.simplefilter('default', DeprecationWarning) # reset filter return func(*args, **kwargs) return decorated return actual_decorator def oauth_url( client_id: Union[int, str], *, permissions: Permissions = MISSING, guild: Snowflake = MISSING, redirect_uri: str = MISSING, scopes: Iterable[str] = MISSING, disable_guild_select: bool = False, ) -> str: """A helper function that returns the OAuth2 URL for inviting the bot into guilds. Parameters ----------- client_id: Union[:class:`int`, :class:`str`] The client ID for your bot. permissions: :class:`~discord.Permissions` The permissions you're requesting. If not given then you won't be requesting any permissions. guild: :class:`~discord.abc.Snowflake` The guild to pre-select in the authorization screen, if available. redirect_uri: :class:`str` An optional valid redirect URI. scopes: Iterable[:class:`str`] An optional valid list of scopes. Defaults to ``('bot',)``. .. versionadded:: 1.7 disable_guild_select: :class:`bool` Whether to disallow the user from changing the guild dropdown. .. versionadded:: 2.0 Returns -------- :class:`str` The OAuth2 URL for inviting the bot into guilds. """ url = f'https://discord.com/oauth2/authorize?client_id={client_id}' url += '&scope=' + '+'.join(scopes or ('bot',)) if permissions is not MISSING: url += f'&permissions={permissions.value}' if guild is not MISSING: url += f'&guild_id={guild.id}' if redirect_uri is not MISSING: from urllib.parse import urlencode url += '&response_type=code&' + urlencode({'redirect_uri': redirect_uri}) if disable_guild_select: url += '&disable_guild_select=true' return url def snowflake_time(id: int) -> datetime.datetime: """ Parameters ----------- id: :class:`int` The snowflake ID. Returns -------- :class:`datetime.datetime` An aware datetime in UTC representing the creation time of the snowflake. """ timestamp = ((id >> 22) + DISCORD_EPOCH) / 1000 return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc) def time_snowflake(dt: datetime.datetime, high: bool = False) -> int: """Returns a numeric snowflake pretending to be created at the given date. When using as the lower end of a range, use ``time_snowflake(high=False) - 1`` to be inclusive, ``high=True`` to be exclusive. When using as the higher end of a range, use ``time_snowflake(high=True) + 1`` to be inclusive, ``high=False`` to be exclusive Parameters ----------- dt: :class:`datetime.datetime` A datetime object to convert to a snowflake. If naive, the timezone is assumed to be local time. high: :class:`bool` Whether or not to set the lower 22 bit to high or low. Returns -------- :class:`int` The snowflake representing the time given. """ discord_millis = int(dt.timestamp() * 1000 - DISCORD_EPOCH) return (discord_millis << 22) + (2 ** 22 - 1 if high else 0) def find(predicate: Callable[[T], Any], seq: Iterable[T]) -> Optional[T]: """A helper to return the first element found in the sequence that meets the predicate. For example: :: member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members) would find the first :class:`~discord.Member` whose name is 'Mighty' and return it. If an entry is not found, then ``None`` is returned. This is different from :func:`py:filter` due to the fact it stops the moment it finds a valid entry. Parameters ----------- predicate A function that returns a boolean-like result. seq: :class:`collections.abc.Iterable` The iterable to search through. """ for element in seq: if predicate(element): return element return None def get(iterable: Iterable[T], **attrs: Any) -> Optional[T]: r"""A helper that returns the first element in the iterable that meets all the traits passed in ``attrs``. This is an alternative for :func:`~discord.utils.find`. When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them. To have a nested attribute search (i.e. search by ``x.y``) then pass in ``x__y`` as the keyword argument. If nothing is found that matches the attributes passed, then ``None`` is returned. Examples --------- Basic usage: .. code-block:: python3 member = discord.utils.get(message.guild.members, name='Foo') Multiple attribute matching: .. code-block:: python3 channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000) Nested attribute matching: .. code-block:: python3 channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general') Parameters ----------- iterable An iterable to search through. \*\*attrs Keyword arguments that denote attributes to search with. """ # global -> local _all = all attrget = attrgetter # Special case the single element call if len(attrs) == 1: k, v = attrs.popitem() pred = attrget(k.replace('__', '.')) for elem in iterable: if pred(elem) == v: return elem return None converted = [(attrget(attr.replace('__', '.')), value) for attr, value in attrs.items()] for elem in iterable: if _all(pred(elem) == value for pred, value in converted): return elem return None def _unique(iterable: Iterable[T]) -> List[T]: return [x for x in dict.fromkeys(iterable)] def _get_as_snowflake(data: Any, key: str) -> Optional[int]: try: value = data[key] except KeyError: return None else: return value and int(value) def _get_mime_type_for_image(data: bytes): if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'): return 'image/png' elif data[0:3] == b'\xff\xd8\xff' or data[6:10] in (b'JFIF', b'Exif'): return 'image/jpeg' elif data.startswith((b'\x47\x49\x46\x38\x37\x61', b'\x47\x49\x46\x38\x39\x61')): return 'image/gif' elif data.startswith(b'RIFF') and data[8:12] == b'WEBP': return 'image/webp' else: raise InvalidArgument('Unsupported image type given') def _bytes_to_base64_data(data: bytes) -> str: fmt = 'data:{mime};base64,{data}' mime = _get_mime_type_for_image(data) b64 = b64encode(data).decode('ascii') return fmt.format(mime=mime, data=b64) if HAS_ORJSON: def _to_json(obj: Any) -> str: # type: ignore return orjson.dumps(obj).decode('utf-8') _from_json = orjson.loads # type: ignore else: def _to_json(obj: Any) -> str: return json.dumps(obj, separators=(',', ':'), ensure_ascii=True) _from_json = json.loads def _parse_ratelimit_header(request: Any, *, use_clock: bool = False) -> float: reset_after: Optional[str] = request.headers.get('X-Ratelimit-Reset-After') if use_clock or not reset_after: utc = datetime.timezone.utc now = datetime.datetime.now(utc) reset = datetime.datetime.fromtimestamp(float(request.headers['X-Ratelimit-Reset']), utc) return (reset - now).total_seconds() else: return float(reset_after) async def maybe_coroutine(f, *args, **kwargs): value = f(*args, **kwargs) if _isawaitable(value): return await value else: return value async def async_all(gen, *, check=_isawaitable): for elem in gen: if check(elem): elem = await elem if not elem: return False return True async def sane_wait_for(futures, *, timeout): ensured = [asyncio.ensure_future(fut) for fut in futures] done, pending = await asyncio.wait(ensured, timeout=timeout, return_when=asyncio.ALL_COMPLETED) if len(pending) != 0: raise asyncio.TimeoutError() return done def get_slots(cls: Type[Any]) -> Iterator[str]: for mro in reversed(cls.__mro__): try: yield from mro.__slots__ except AttributeError: continue def compute_timedelta(dt: datetime.datetime): if dt.tzinfo is None: dt = dt.astimezone() now = datetime.datetime.now(datetime.timezone.utc) return max((dt - now).total_seconds(), 0) async def sleep_until(when: datetime.datetime, result: Optional[T] = None) -> Optional[T]: """|coro| Sleep until a specified time. If the time supplied is in the past this function will yield instantly. .. versionadded:: 1.3 Parameters ----------- when: :class:`datetime.datetime` The timestamp in which to sleep until. If the datetime is naive then it is assumed to be local time. result: Any If provided is returned to the caller when the coroutine completes. """ delta = compute_timedelta(when) return await asyncio.sleep(delta, result) def utcnow() -> datetime.datetime: """A helper function to return an aware UTC datetime representing the current time. This should be preferred to :meth:`datetime.datetime.utcnow` since it is an aware datetime, compared to the naive datetime in the standard library. .. versionadded:: 2.0 Returns -------- :class:`datetime.datetime` The current aware datetime in UTC. """ return datetime.datetime.now(datetime.timezone.utc) def valid_icon_size(size: int) -> bool: """Icons must be power of 2 within [16, 4096].""" return not size & (size - 1) and 4096 >= size >= 16 class SnowflakeList(array.array): """Internal data storage class to efficiently store a list of snowflakes. This should have the following characteristics: - Low memory usage - O(n) iteration (obviously) - O(n log n) initial creation if data is unsorted - O(log n) search and indexing - O(n) insertion """ __slots__ = () if TYPE_CHECKING: def __init__(self, data: Iterable[int], *, is_sorted: bool = False): ... def __new__(cls, data: Iterable[int], *, is_sorted: bool = False): return array.array.__new__(cls, 'Q', data if is_sorted else sorted(data)) # type: ignore def add(self, element: int) -> None: i = bisect_left(self, element) self.insert(i, element) def get(self, element: int) -> Optional[int]: i = bisect_left(self, element) return self[i] if i != len(self) and self[i] == element else None def has(self, element: int) -> bool: i = bisect_left(self, element) return i != len(self) and self[i] == element _IS_ASCII = re.compile(r'^[\x00-\x7f]+$') def _string_width(string: str, *, _IS_ASCII=_IS_ASCII) -> int: """Returns string's width.""" match = _IS_ASCII.match(string) if match: return match.endpos UNICODE_WIDE_CHAR_TYPE = 'WFA' func = unicodedata.east_asian_width return sum(2 if func(char) in UNICODE_WIDE_CHAR_TYPE else 1 for char in string) def resolve_invite(invite: Union[Invite, str]) -> str: """ Resolves an invite from a :class:`~discord.Invite`, URL or code. Parameters ----------- invite: Union[:class:`~discord.Invite`, :class:`str`] The invite. Returns -------- :class:`str` The invite code. """ from .invite import Invite # circular import if isinstance(invite, Invite): return invite.code else: rx = r'(?:https?\:\/\/)?discord(?:\.gg|(?:app)?\.com\/invite)\/(.+)' m = re.match(rx, invite) if m: return m.group(1) return invite def resolve_template(code: Union[Template, str]) -> str: """ Resolves a template code from a :class:`~discord.Template`, URL or code. .. versionadded:: 1.4 Parameters ----------- code: Union[:class:`~discord.Template`, :class:`str`] The code. Returns -------- :class:`str` The template code. """ from .template import Template # circular import if isinstance(code, Template): return code.code else: rx = r'(?:https?\:\/\/)?discord(?:\.new|(?:app)?\.com\/template)\/(.+)' m = re.match(rx, code) if m: return m.group(1) return code _MARKDOWN_ESCAPE_SUBREGEX = '|'.join(r'\{0}(?=([\s\S]*((?<!\{0})\{0})))'.format(c) for c in ('*', '`', '_', '~', '|')) _MARKDOWN_ESCAPE_COMMON = r'^>(?:>>)?\s|\[.+\]\(.+\)' _MARKDOWN_ESCAPE_REGEX = re.compile(fr'(?P<markdown>{_MARKDOWN_ESCAPE_SUBREGEX}|{_MARKDOWN_ESCAPE_COMMON})', re.MULTILINE) _URL_REGEX = r'(?P<url><[^: >]+:\/[^ >]+>|(?:https?|steam):\/\/[^\s<]+[^<.,:;\"\'\]\s])' _MARKDOWN_STOCK_REGEX = fr'(?P<markdown>[_\\~|\*`]|{_MARKDOWN_ESCAPE_COMMON})' def remove_markdown(text: str, *, ignore_links: bool = True) -> str: """A helper function that removes markdown characters. .. versionadded:: 1.7 .. note:: This function is not markdown aware and may remove meaning from the original text. For example, if the input contains ``10 * 5`` then it will be converted into ``10 5``. Parameters ----------- text: :class:`str` The text to remove markdown from. ignore_links: :class:`bool` Whether to leave links alone when removing markdown. For example, if a URL in the text contains characters such as ``_`` then it will be left alone. Defaults to ``True``. Returns -------- :class:`str` The text with the markdown special characters removed. """ def replacement(match): groupdict = match.groupdict() return groupdict.get('url', '') regex = _MARKDOWN_STOCK_REGEX if ignore_links: regex = f'(?:{_URL_REGEX}|{regex})' return re.sub(regex, replacement, text, 0, re.MULTILINE) def escape_markdown(text: str, *, as_needed: bool = False, ignore_links: bool = True) -> str: r"""A helper function that escapes Discord's markdown. Parameters ----------- text: :class:`str` The text to escape markdown from. as_needed: :class:`bool` Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it's not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**`` instead of ``\*\*hello\*\*``. Note however that this can open you up to some clever syntax abuse. Defaults to ``False``. ignore_links: :class:`bool` Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as ``_`` then it will be left alone. This option is not supported with ``as_needed``. Defaults to ``True``. Returns -------- :class:`str` The text with the markdown special characters escaped with a slash. """ if not as_needed: def replacement(match): groupdict = match.groupdict() is_url = groupdict.get('url') if is_url: return is_url return '\\' + groupdict['markdown'] regex = _MARKDOWN_STOCK_REGEX if ignore_links: regex = f'(?:{_URL_REGEX}|{regex})' return re.sub(regex, replacement, text, 0, re.MULTILINE) else: text = re.sub(r'\\', r'\\\\', text) return _MARKDOWN_ESCAPE_REGEX.sub(r'\\\1', text) def escape_mentions(text: str) -> str: """A helper function that escapes everyone, here, role, and user mentions. .. note:: This does not include channel mentions. .. note:: For more granular control over what mentions should be escaped within messages, refer to the :class:`~discord.AllowedMentions` class. Parameters ----------- text: :class:`str` The text to escape mentions from. Returns -------- :class:`str` The text with the mentions removed. """ return re.sub(r'@(everyone|here|[!&]?[0-9]{17,20})', '@\u200b\\1', text) 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 @overload def as_chunks(iterator: Iterator[T], max_size: int) -> Iterator[List[T]]: ... @overload def as_chunks(iterator: AsyncIterator[T], max_size: int) -> AsyncIterator[List[T]]: ... 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) PY_310 = sys.version_info >= (3, 10) def flatten_literal_params(parameters: Iterable[Any]) -> Tuple[Any, ...]: params = [] literal_cls = type(Literal[0]) for p in parameters: if isinstance(p, literal_cls): params.extend(p.__args__) else: params.append(p) return tuple(params) def normalise_optional_params(parameters: Iterable[Any]) -> Tuple[Any, ...]: none_cls = type(None) return tuple(p for p in parameters if p is not none_cls) + (none_cls,) def evaluate_annotation( tp: Any, globals: Dict[str, Any], locals: Dict[str, Any], cache: Dict[str, Any], *, implicit_str: bool = True, ): if isinstance(tp, ForwardRef): tp = tp.__forward_arg__ # ForwardRefs always evaluate their internals implicit_str = True if implicit_str and isinstance(tp, str): if tp in cache: return cache[tp] evaluated = eval(tp, globals, locals) cache[tp] = evaluated return evaluate_annotation(evaluated, globals, locals, cache) if hasattr(tp, '__args__'): implicit_str = True is_literal = False args = tp.__args__ if not hasattr(tp, '__origin__'): if PY_310 and tp.__class__ is types.UnionType: # type: ignore converted = Union[args] # type: ignore return evaluate_annotation(converted, globals, locals, cache) return tp if tp.__origin__ is Union: try: if args.index(type(None)) != len(args) - 1: args = normalise_optional_params(tp.__args__) except ValueError: pass if tp.__origin__ is Literal: if not PY_310: args = flatten_literal_params(tp.__args__) implicit_str = False is_literal = True evaluated_args = tuple(evaluate_annotation(arg, globals, locals, cache, implicit_str=implicit_str) for arg in args) if is_literal and not all(isinstance(x, (str, int, bool, type(None))) for x in evaluated_args): raise TypeError('Literal arguments must be of type str, int, bool, or NoneType.') if evaluated_args == args: return tp try: return tp.copy_with(evaluated_args) except AttributeError: return tp.__origin__[evaluated_args] return tp def resolve_annotation( annotation: Any, globalns: Dict[str, Any], localns: Optional[Dict[str, Any]], cache: Optional[Dict[str, Any]], ) -> Any: if annotation is None: return type(None) if isinstance(annotation, str): annotation = ForwardRef(annotation) locals = globalns if localns is None else localns if cache is None: cache = {} return evaluate_annotation(annotation, globalns, locals, cache) TimestampStyle = Literal['f', 'F', 'd', 'D', 't', 'T', 'R'] 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 style is None: return f'<t:{int(dt.timestamp())}>' return f'<t:{int(dt.timestamp())}:{style}>'
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/utils.py
utils.py
from __future__ import annotations from typing import Type, TypeVar, Union, List, TYPE_CHECKING, Any, Union __all__ = ( 'AllowedMentions', ) if TYPE_CHECKING: from .types.message import AllowedMentions as AllowedMentionsPayload from .abc import Snowflake class _FakeBool: def __repr__(self): return 'True' def __eq__(self, other): return other is True def __bool__(self): return True default: Any = _FakeBool() A = TypeVar('A', bound='AllowedMentions') class AllowedMentions: """A class that represents what mentions are allowed in a message. This class can be set during :class:`Client` initialisation to apply to every message sent. It can also be applied on a per message basis via :meth:`abc.Messageable.send` for more fine-grained control. Attributes ------------ everyone: :class:`bool` Whether to allow everyone and here mentions. Defaults to ``True``. users: Union[:class:`bool`, List[:class:`abc.Snowflake`]] Controls the users being mentioned. If ``True`` (the default) then users are mentioned based on the message content. If ``False`` then users are not mentioned at all. If a list of :class:`abc.Snowflake` is given then only the users provided will be mentioned, provided those users are in the message content. roles: Union[:class:`bool`, List[:class:`abc.Snowflake`]] Controls the roles being mentioned. If ``True`` (the default) then roles are mentioned based on the message content. If ``False`` then roles are not mentioned at all. If a list of :class:`abc.Snowflake` is given then only the roles provided will be mentioned, provided those roles are in the message content. replied_user: :class:`bool` Whether to mention the author of the message being replied to. Defaults to ``True``. .. versionadded:: 1.6 """ __slots__ = ('everyone', 'users', 'roles', 'replied_user') def __init__( self, *, everyone: bool = default, users: Union[bool, List[Snowflake]] = default, roles: Union[bool, List[Snowflake]] = default, replied_user: bool = default, ): self.everyone = everyone self.users = users self.roles = roles self.replied_user = replied_user @classmethod def all(cls: Type[A]) -> A: """A factory method that returns a :class:`AllowedMentions` with all fields explicitly set to ``True`` .. versionadded:: 1.5 """ return cls(everyone=True, users=True, roles=True, replied_user=True) @classmethod def none(cls: Type[A]) -> A: """A factory method that returns a :class:`AllowedMentions` with all fields set to ``False`` .. versionadded:: 1.5 """ return cls(everyone=False, users=False, roles=False, replied_user=False) def to_dict(self) -> AllowedMentionsPayload: parse = [] data = {} if self.everyone: parse.append('everyone') if self.users == True: parse.append('users') elif self.users != False: data['users'] = [x.id for x in self.users] if self.roles == True: parse.append('roles') elif self.roles != False: data['roles'] = [x.id for x in self.roles] if self.replied_user: data['replied_user'] = True data['parse'] = parse return data # type: ignore def merge(self, other: AllowedMentions) -> AllowedMentions: # Creates a new AllowedMentions by merging from another one. # Merge is done by using the 'self' values unless explicitly # overridden by the 'other' values. everyone = self.everyone if other.everyone is default else other.everyone users = self.users if other.users is default else other.users roles = self.roles if other.roles is default else other.roles replied_user = self.replied_user if other.replied_user is default else other.replied_user return AllowedMentions(everyone=everyone, roles=roles, users=users, replied_user=replied_user) def __repr__(self) -> str: return ( f'{self.__class__.__name__}(everyone={self.everyone}, ' f'users={self.users}, roles={self.roles}, replied_user={self.replied_user})' )
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/mentions.py
mentions.py
from __future__ import annotations from typing import Any, Dict, List, Optional, Type, TypeVar, TYPE_CHECKING import discord.abc from .asset import Asset from .colour import Colour from .enums import DefaultAvatar from .flags import PublicUserFlags from .utils import snowflake_time, _bytes_to_base64_data, MISSING if TYPE_CHECKING: from datetime import datetime from .channel import DMChannel from .guild import Guild from .message import Message from .state import ConnectionState from .types.channel import DMChannel as DMChannelPayload from .types.user import User as UserPayload __all__ = ( 'User', 'ClientUser', ) BU = TypeVar('BU', bound='BaseUser') class _UserTag: __slots__ = () id: int class BaseUser(_UserTag): __slots__ = ( 'name', 'id', 'discriminator', '_avatar', '_banner', '_accent_colour', 'bot', 'system', '_public_flags', '_state', ) if TYPE_CHECKING: name: str id: int discriminator: str bot: bool system: bool _state: ConnectionState _avatar: Optional[str] _banner: Optional[str] _accent_colour: Optional[str] _public_flags: int def __init__(self, *, state: ConnectionState, data: UserPayload) -> None: self._state = state self._update(data) def __repr__(self) -> str: return ( f"<BaseUser id={self.id} name={self.name!r} discriminator={self.discriminator!r}" f" bot={self.bot} system={self.system}>" ) def __str__(self) -> str: return f'{self.name}#{self.discriminator}' 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: 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) @classmethod def _copy(cls: Type[BU], user: BU) -> BU: 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, 'discriminator': self.discriminator, 'bot': self.bot, } @property def public_flags(self) -> PublicUserFlags: """:class:`PublicUserFlags`: The publicly available flags the user has.""" return PublicUserFlags._from_value(self._public_flags) @property 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 @property def default_avatar(self) -> Asset: """:class:`Asset`: Returns the default avatar for a given user. This is calculated by the user's discriminator.""" return Asset._from_default_avatar(self._state, int(self.discriminator) % len(DefaultAvatar)) @property 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 @property 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) @property 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(self._accent_colour) @property 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 @property 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() @property 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 @property def mention(self) -> str: """:class:`str`: Returns a string that allows you to mention the given user.""" return f'<@{self.id}>' @property 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) @property 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 ClientUser(BaseUser): """Represents your 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. discriminator: :class:`str` The user's discriminator. This is given when the username has conflicts. 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). .. versionadded:: 1.3 verified: :class:`bool` Specifies if the user's email is verified. locale: Optional[:class:`str`] The IETF language tag used to identify the language the user is using. mfa_enabled: :class:`bool` Specifies if the user has MFA turned on and working. """ __slots__ = ('locale', '_flags', 'verified', 'mfa_enabled', '__weakref__') if TYPE_CHECKING: verified: bool locale: Optional[str] mfa_enabled: bool _flags: int def __init__(self, *, state: ConnectionState, data: UserPayload) -> None: super().__init__(state=state, data=data) def __repr__(self) -> str: return ( f'<ClientUser id={self.id} name={self.name!r} discriminator={self.discriminator!r}' f' bot={self.bot} verified={self.verified} mfa_enabled={self.mfa_enabled}>' ) def _update(self, data: UserPayload) -> None: super()._update(data) # There's actually an Optional[str] phone field as well but I won't use it self.verified = data.get('verified', False) self.locale = data.get('locale') self._flags = data.get('flags', 0) self.mfa_enabled = data.get('mfa_enabled', False) async def edit(self, *, username: str = MISSING, avatar: bytes = MISSING) -> ClientUser: """|coro| Edits the current profile of the client. .. note:: To upload an avatar, a :term:`py:bytes-like object` must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via ``open('some_filename', 'rb')`` and the :term:`py:bytes-like object` is given through the use of ``fp.read()``. The only image formats supported for uploading is JPEG and PNG. .. versionchanged:: 2.0 The edit is no longer in-place, instead the newly edited client user is returned. Parameters ----------- username: :class:`str` The new username you wish to change to. avatar: :class:`bytes` A :term:`py:bytes-like object` representing the image to upload. Could be ``None`` to denote no avatar. Raises ------ HTTPException Editing your profile failed. InvalidArgument Wrong image format passed for ``avatar``. Returns --------- :class:`ClientUser` The newly edited client user. """ payload: Dict[str, Any] = {} if username is not MISSING: payload['username'] = username if avatar is not MISSING: payload['avatar'] = _bytes_to_base64_data(avatar) data: UserPayload = await self._state.http.edit_profile(payload) return ClientUser(state=self._state, data=data) class User(BaseUser, discord.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. discriminator: :class:`str` The user's discriminator. This is given when the username has conflicts. 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: 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} discriminator={self.discriminator!r} bot={self.bot}>' def __del__(self) -> None: try: if self._stored: self._state.deref_user(self.id) except Exception: pass @classmethod def _copy(cls, user: User): self = super()._copy(user) self._stored = False return self async def _get_channel(self) -> DMChannel: ch = await self.create_dm() return ch @property 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) @property 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)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/user.py
user.py
from __future__ import annotations from typing import Any, TYPE_CHECKING, Union, Optional from .iterators import ReactionIterator __all__ = ( 'Reaction', ) if TYPE_CHECKING: from .types.message import Reaction as ReactionPayload from .message import Message from .partial_emoji import PartialEmoji from .emoji import Emoji from .abc import Snowflake class Reaction: """Represents a reaction to a message. Depending on the way this object was created, some of the attributes can have a value of ``None``. .. container:: operations .. describe:: x == y Checks if two reactions are equal. This works by checking if the emoji is the same. So two messages with the same reaction will be considered "equal". .. describe:: x != y Checks if two reactions are not equal. .. describe:: hash(x) Returns the reaction's hash. .. describe:: str(x) Returns the string form of the reaction's emoji. Attributes ----------- emoji: Union[:class:`Emoji`, :class:`PartialEmoji`, :class:`str`] The reaction emoji. May be a custom emoji, or a unicode emoji. count: :class:`int` Number of times this reaction was made me: :class:`bool` If the user sent this reaction. message: :class:`Message` Message this reaction is for. """ __slots__ = ('message', 'count', 'emoji', 'me') def __init__(self, *, message: Message, data: ReactionPayload, emoji: Optional[Union[PartialEmoji, Emoji, str]] = None): self.message: Message = message self.emoji: Union[PartialEmoji, Emoji, str] = emoji or message._state.get_reaction_emoji(data['emoji']) self.count: int = data.get('count', 1) self.me: bool = data.get('me') # TODO: typeguard def is_custom_emoji(self) -> bool: """:class:`bool`: If this is a custom emoji.""" return not isinstance(self.emoji, str) def __eq__(self, other: Any) -> bool: return isinstance(other, self.__class__) and other.emoji == self.emoji def __ne__(self, other: Any) -> bool: if isinstance(other, self.__class__): return other.emoji != self.emoji return True def __hash__(self) -> int: return hash(self.emoji) def __str__(self) -> str: return str(self.emoji) def __repr__(self) -> str: return f'<Reaction emoji={self.emoji!r} me={self.me} count={self.count}>' async def remove(self, user: Snowflake) -> None: """|coro| Remove the reaction by the provided :class:`User` from the message. If the reaction is not your own (i.e. ``user`` parameter is not you) then the :attr:`~Permissions.manage_messages` permission is needed. The ``user`` parameter must represent a user or member and meet the :class:`abc.Snowflake` abc. Parameters ----------- user: :class:`abc.Snowflake` The user or member from which to remove the reaction. Raises ------- HTTPException Removing the reaction failed. Forbidden You do not have the proper permissions to remove the reaction. NotFound The user you specified, or the reaction's message was not found. """ await self.message.remove_reaction(self.emoji, user) async def clear(self) -> None: """|coro| Clears this reaction from the message. You need the :attr:`~Permissions.manage_messages` permission to use this. .. versionadded:: 1.3 Raises -------- HTTPException Clearing the reaction failed. Forbidden You do not have the proper permissions to clear the reaction. NotFound The emoji you specified was not found. InvalidArgument The emoji parameter is invalid. """ await self.message.clear_reaction(self.emoji) def users(self, *, limit: Optional[int] = None, after: Optional[Snowflake] = None) -> ReactionIterator: """Returns an :class:`AsyncIterator` representing the users that have reacted to the message. The ``after`` parameter must represent a member and meet the :class:`abc.Snowflake` abc. Examples --------- Usage :: # I do not actually recommend doing this. async for user in reaction.users(): await channel.send(f'{user} has reacted with {reaction.emoji}!') Flattening into a list: :: users = await reaction.users().flatten() # users is now a list of User... winner = random.choice(users) await channel.send(f'{winner} has won the raffle.') Parameters ------------ limit: Optional[:class:`int`] The maximum number of results to return. If not provided, returns all the users who reacted to the message. after: Optional[:class:`abc.Snowflake`] For pagination, reactions are sorted by member. Raises -------- HTTPException Getting the users for the reaction failed. Yields -------- Union[:class:`User`, :class:`Member`] The member (if retrievable) or the user that has reacted to this message. The case where it can be a :class:`Member` is in a guild message context. Sometimes it can be a :class:`User` if the member has left the guild. """ if not isinstance(self.emoji, str): emoji = f'{self.emoji.name}:{self.emoji.id}' else: emoji = self.emoji if limit is None: limit = self.count return ReactionIterator(self.message, emoji, limit, after)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/reaction.py
reaction.py
from __future__ import annotations import asyncio import datetime from typing import Awaitable, TYPE_CHECKING, TypeVar, Optional, Any, Callable, Union, List, AsyncIterator from .errors import NoMoreItems from .utils import snowflake_time, time_snowflake, maybe_coroutine from .object import Object from .audit_logs import AuditLogEntry __all__ = ( 'ReactionIterator', 'HistoryIterator', 'AuditLogIterator', 'GuildIterator', 'MemberIterator', ) if TYPE_CHECKING: from .types.audit_log import ( AuditLog as AuditLogPayload, ) from .types.guild import ( Guild as GuildPayload, ) from .types.message import ( Message as MessagePayload, ) from .types.user import ( PartialUser as PartialUserPayload, ) from .types.threads import ( Thread as ThreadPayload, ) from .member import Member from .user import User from .message import Message from .audit_logs import AuditLogEntry from .guild import Guild from .threads import Thread from .abc import Snowflake T = TypeVar('T') OT = TypeVar('OT') _Func = Callable[[T], Union[OT, Awaitable[OT]]] OLDEST_OBJECT = Object(id=0) class _AsyncIterator(AsyncIterator[T]): __slots__ = () async def next(self) -> T: raise NotImplementedError def get(self, **attrs: Any) -> Awaitable[Optional[T]]: def predicate(elem: T): for attr, val in attrs.items(): nested = attr.split('__') obj = elem for attribute in nested: obj = getattr(obj, attribute) if obj != val: return False return True return self.find(predicate) async def find(self, predicate: _Func[T, bool]) -> Optional[T]: while True: try: elem = await self.next() except NoMoreItems: return None ret = await maybe_coroutine(predicate, elem) if ret: return elem def chunk(self, max_size: int) -> _ChunkedAsyncIterator[T]: if max_size <= 0: raise ValueError('async iterator chunk sizes must be greater than 0.') return _ChunkedAsyncIterator(self, max_size) def map(self, func: _Func[T, OT]) -> _MappedAsyncIterator[OT]: return _MappedAsyncIterator(self, func) def filter(self, predicate: _Func[T, bool]) -> _FilteredAsyncIterator[T]: return _FilteredAsyncIterator(self, predicate) async def flatten(self) -> List[T]: return [element async for element in self] async def __anext__(self) -> T: try: return await self.next() except NoMoreItems: raise StopAsyncIteration() def _identity(x): return x class _ChunkedAsyncIterator(_AsyncIterator[List[T]]): def __init__(self, iterator, max_size): self.iterator = iterator self.max_size = max_size async def next(self) -> List[T]: ret: List[T] = [] n = 0 while n < self.max_size: try: item = await self.iterator.next() except NoMoreItems: if ret: return ret raise else: ret.append(item) n += 1 return ret class _MappedAsyncIterator(_AsyncIterator[T]): def __init__(self, iterator, func): self.iterator = iterator self.func = func async def next(self) -> T: # this raises NoMoreItems and will propagate appropriately item = await self.iterator.next() return await maybe_coroutine(self.func, item) class _FilteredAsyncIterator(_AsyncIterator[T]): def __init__(self, iterator, predicate): self.iterator = iterator if predicate is None: predicate = _identity self.predicate = predicate async def next(self) -> T: getter = self.iterator.next pred = self.predicate while True: # propagate NoMoreItems similar to _MappedAsyncIterator item = await getter() ret = await maybe_coroutine(pred, item) if ret: return item class ReactionIterator(_AsyncIterator[Union['User', 'Member']]): def __init__(self, message, emoji, limit=100, after=None): self.message = message self.limit = limit self.after = after state = message._state self.getter = state.http.get_reaction_users self.state = state self.emoji = emoji self.guild = message.guild self.channel_id = message.channel.id self.users = asyncio.Queue() async def next(self) -> Union[User, Member]: if self.users.empty(): await self.fill_users() try: return self.users.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() async def fill_users(self): # this is a hack because >circular imports< from .user import User if self.limit > 0: retrieve = self.limit if self.limit <= 100 else 100 after = self.after.id if self.after else None data: List[PartialUserPayload] = await self.getter( self.channel_id, self.message.id, self.emoji, retrieve, after=after ) if data: self.limit -= retrieve self.after = Object(id=int(data[-1]['id'])) if self.guild is None or isinstance(self.guild, Object): for element in reversed(data): await self.users.put(User(state=self.state, data=element)) else: for element in reversed(data): member_id = int(element['id']) member = self.guild.get_member(member_id) if member is not None: await self.users.put(member) else: await self.users.put(User(state=self.state, data=element)) class HistoryIterator(_AsyncIterator['Message']): """Iterator for receiving a channel's message history. The messages endpoint has two behaviours we care about here: If ``before`` is specified, the messages endpoint returns the `limit` newest messages before ``before``, sorted with newest first. For filling over 100 messages, update the ``before`` parameter to the oldest message received. Messages will be returned in order by time. If ``after`` is specified, it returns the ``limit`` oldest messages after ``after``, sorted with newest first. For filling over 100 messages, update the ``after`` parameter to the newest message received. If messages are not reversed, they will be out of order (99-0, 199-100, so on) A note that if both ``before`` and ``after`` are specified, ``before`` is ignored by the messages endpoint. Parameters ----------- messageable: :class:`abc.Messageable` Messageable class to retrieve message history from. limit: :class:`int` Maximum number of messages to retrieve before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Message before which all messages must be. after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Message after which all messages must be. around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Message around which all messages must be. Limit max 101. Note that if limit is an even number, this will return at most limit+1 messages. oldest_first: Optional[:class:`bool`] If set to ``True``, return messages in oldest->newest order. Defaults to ``True`` if `after` is specified, otherwise ``False``. """ def __init__(self, messageable, limit, before=None, after=None, around=None, oldest_first=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) if isinstance(around, datetime.datetime): around = Object(id=time_snowflake(around)) if oldest_first is None: self.reverse = after is not None else: self.reverse = oldest_first self.messageable = messageable self.limit = limit self.before = before self.after = after or OLDEST_OBJECT self.around = around self._filter = None # message dict -> bool self.state = self.messageable._state self.logs_from = self.state.http.logs_from self.messages = asyncio.Queue() if self.around: if self.limit is None: raise ValueError('history does not support around with limit=None') if self.limit > 101: raise ValueError("history max limit 101 when specifying around parameter") elif self.limit == 101: self.limit = 100 # Thanks discord self._retrieve_messages = self._retrieve_messages_around_strategy # type: ignore if self.before and self.after: self._filter = lambda m: self.after.id < int(m['id']) < self.before.id elif self.before: self._filter = lambda m: int(m['id']) < self.before.id elif self.after: self._filter = lambda m: self.after.id < int(m['id']) else: if self.reverse: self._retrieve_messages = self._retrieve_messages_after_strategy # type: ignore if self.before: self._filter = lambda m: int(m['id']) < self.before.id else: self._retrieve_messages = self._retrieve_messages_before_strategy # type: ignore if self.after and self.after != OLDEST_OBJECT: self._filter = lambda m: int(m['id']) > self.after.id async def next(self) -> Message: if self.messages.empty(): await self.fill_messages() try: return self.messages.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 async def fill_messages(self): if not hasattr(self, 'channel'): # do the required set up channel = await self.messageable._get_channel() self.channel = channel if self._get_retrieve(): data = await self._retrieve_messages(self.retrieve) if len(data) < 100: self.limit = 0 # terminate the infinite loop if self.reverse: data = reversed(data) if self._filter: data = filter(self._filter, data) channel = self.channel for element in data: await self.messages.put(self.state.create_message(channel=channel, data=element)) async def _retrieve_messages(self, retrieve) -> List[Message]: """Retrieve messages and update next parameters.""" raise NotImplementedError async def _retrieve_messages_before_strategy(self, retrieve): """Retrieve messages using before parameter.""" before = self.before.id if self.before else None data: List[MessagePayload] = await self.logs_from(self.channel.id, retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data async def _retrieve_messages_after_strategy(self, retrieve): """Retrieve messages using after parameter.""" after = self.after.id if self.after else None data: List[MessagePayload] = await self.logs_from(self.channel.id, retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data async def _retrieve_messages_around_strategy(self, retrieve): """Retrieve messages using around parameter.""" if self.around: around = self.around.id if self.around else None data: List[MessagePayload] = await self.logs_from(self.channel.id, retrieve, around=around) self.around = None return data return [] class AuditLogIterator(_AsyncIterator['AuditLogEntry']): def __init__(self, guild, limit=None, before=None, after=None, oldest_first=None, user_id=None, action_type=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) if oldest_first is None: self.reverse = after is not None else: self.reverse = oldest_first self.guild = guild self.loop = guild._state.loop self.request = guild._state.http.get_audit_logs self.limit = limit self.before = before self.user_id = user_id self.action_type = action_type self.after = OLDEST_OBJECT self._users = {} self._state = guild._state self._filter = None # entry dict -> bool self.entries = asyncio.Queue() if self.reverse: self._strategy = self._after_strategy if self.before: self._filter = lambda m: int(m['id']) < self.before.id else: self._strategy = self._before_strategy if self.after and self.after != OLDEST_OBJECT: self._filter = lambda m: int(m['id']) > self.after.id async def _before_strategy(self, retrieve): before = self.before.id if self.before else None data: AuditLogPayload = await self.request( self.guild.id, limit=retrieve, user_id=self.user_id, action_type=self.action_type, before=before ) entries = data.get('audit_log_entries', []) if len(data) and entries: if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(entries[-1]['id'])) return data.get('users', []), entries async def _after_strategy(self, retrieve): after = self.after.id if self.after else None data: AuditLogPayload = await self.request( self.guild.id, limit=retrieve, user_id=self.user_id, action_type=self.action_type, after=after ) entries = data.get('audit_log_entries', []) if len(data) and entries: if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(entries[0]['id'])) return data.get('users', []), entries async def next(self) -> AuditLogEntry: if self.entries.empty(): await self._fill() try: return self.entries.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 async def _fill(self): from .user import User if self._get_retrieve(): users, data = await self._strategy(self.retrieve) if len(data) < 100: self.limit = 0 # terminate the infinite loop if self.reverse: data = reversed(data) if self._filter: data = filter(self._filter, data) for user in users: u = User(data=user, state=self._state) self._users[u.id] = u for element in data: # TODO: remove this if statement later if element['action_type'] is None: continue await self.entries.put(AuditLogEntry(data=element, users=self._users, guild=self.guild)) class GuildIterator(_AsyncIterator['Guild']): """Iterator for receiving the client's guilds. The guilds endpoint has the same two behaviours as described in :class:`HistoryIterator`: If ``before`` is specified, the guilds endpoint returns the ``limit`` newest guilds before ``before``, sorted with newest first. For filling over 100 guilds, update the ``before`` parameter to the oldest guild received. Guilds will be returned in order by time. If `after` is specified, it returns the ``limit`` oldest guilds after ``after``, sorted with newest first. For filling over 100 guilds, update the ``after`` parameter to the newest guild received, If guilds are not reversed, they will be out of order (99-0, 199-100, so on) Not that if both ``before`` and ``after`` are specified, ``before`` is ignored by the guilds endpoint. Parameters ----------- bot: :class:`discord.Client` The client to retrieve the guilds from. limit: :class:`int` Maximum number of guilds to retrieve. before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Object before which all guilds must be. after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Object after which all guilds must be. """ def __init__(self, bot, limit, before=None, after=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) self.bot = bot self.limit = limit self.before = before self.after = after self._filter = None self.state = self.bot._connection self.get_guilds = self.bot.http.get_guilds self.guilds = asyncio.Queue() if self.before and self.after: self._retrieve_guilds = self._retrieve_guilds_before_strategy # type: ignore self._filter = lambda m: int(m['id']) > self.after.id elif self.after: self._retrieve_guilds = self._retrieve_guilds_after_strategy # type: ignore else: self._retrieve_guilds = self._retrieve_guilds_before_strategy # type: ignore async def next(self) -> Guild: if self.guilds.empty(): await self.fill_guilds() try: return self.guilds.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 def create_guild(self, data): from .guild import Guild return Guild(state=self.state, data=data) async def fill_guilds(self): if self._get_retrieve(): data = await self._retrieve_guilds(self.retrieve) if self.limit is None or len(data) < 100: self.limit = 0 if self._filter: data = filter(self._filter, data) for element in data: await self.guilds.put(self.create_guild(element)) async def _retrieve_guilds(self, retrieve) -> List[Guild]: """Retrieve guilds and update next parameters.""" raise NotImplementedError async def _retrieve_guilds_before_strategy(self, retrieve): """Retrieve guilds using before parameter.""" before = self.before.id if self.before else None data: List[GuildPayload] = await self.get_guilds(retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data async def _retrieve_guilds_after_strategy(self, retrieve): """Retrieve guilds using after parameter.""" after = self.after.id if self.after else None data: List[GuildPayload] = await self.get_guilds(retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data class MemberIterator(_AsyncIterator['Member']): def __init__(self, guild, limit=1000, after=None): if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) self.guild = guild self.limit = limit self.after = after or OLDEST_OBJECT self.state = self.guild._state self.get_members = self.state.http.get_members self.members = asyncio.Queue() async def next(self) -> Member: if self.members.empty(): await self.fill_members() try: return self.members.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 1000: r = 1000 else: r = l self.retrieve = r return r > 0 async def fill_members(self): if self._get_retrieve(): after = self.after.id if self.after else None data = await self.get_members(self.guild.id, self.retrieve, after) if not data: # no data, terminate return if len(data) < 1000: self.limit = 0 # terminate loop self.after = Object(id=int(data[-1]['user']['id'])) for element in reversed(data): await self.members.put(self.create_member(element)) def create_member(self, data): from .member import Member return Member(data=data, guild=self.guild, state=self.state) class ArchivedThreadIterator(_AsyncIterator['Thread']): def __init__( self, channel_id: int, guild: Guild, limit: Optional[int], joined: bool, private: bool, before: Optional[Union[Snowflake, datetime.datetime]] = None, ): self.channel_id = channel_id self.guild = guild self.limit = limit self.joined = joined self.private = private self.http = guild._state.http if joined and not private: raise ValueError('Cannot iterate over joined public archived threads') self.before: Optional[str] if before is None: self.before = None elif isinstance(before, datetime.datetime): if joined: self.before = str(time_snowflake(before, high=False)) else: self.before = before.isoformat() else: if joined: self.before = str(before.id) else: self.before = snowflake_time(before.id).isoformat() self.update_before: Callable[[ThreadPayload], str] = self.get_archive_timestamp if joined: self.endpoint = self.http.get_joined_private_archived_threads self.update_before = self.get_thread_id elif private: self.endpoint = self.http.get_private_archived_threads else: self.endpoint = self.http.get_public_archived_threads self.queue: asyncio.Queue[Thread] = asyncio.Queue() self.has_more: bool = True async def next(self) -> Thread: if self.queue.empty(): await self.fill_queue() try: return self.queue.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() @staticmethod def get_archive_timestamp(data: ThreadPayload) -> str: return data['thread_metadata']['archive_timestamp'] @staticmethod def get_thread_id(data: ThreadPayload) -> str: return data['id'] # type: ignore async def fill_queue(self) -> None: if not self.has_more: raise NoMoreItems() limit = 50 if self.limit is None else max(self.limit, 50) data = await self.endpoint(self.channel_id, before=self.before, limit=limit) # This stuff is obviously WIP because 'members' is always empty threads: List[ThreadPayload] = data.get('threads', []) for d in reversed(threads): self.queue.put_nowait(self.create_thread(d)) self.has_more = data.get('has_more', False) if self.limit is not None: self.limit -= len(threads) if self.limit <= 0: self.has_more = False if self.has_more: self.before = self.update_before(threads[-1]) def create_thread(self, data: ThreadPayload) -> Thread: from .threads import Thread return Thread(guild=self.guild, state=self.guild._state, data=data)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/iterators.py
iterators.py
from __future__ import annotations from typing import Any, Optional, TYPE_CHECKING from .utils import parse_time, _get_as_snowflake, _bytes_to_base64_data, MISSING from .enums import VoiceRegion from .guild import Guild __all__ = ( 'Template', ) if TYPE_CHECKING: import datetime from .types.template import Template as TemplatePayload from .state import ConnectionState from .user import User class _FriendlyHttpAttributeErrorHelper: __slots__ = () def __getattr__(self, attr): raise AttributeError('PartialTemplateState does not support http methods.') class _PartialTemplateState: def __init__(self, *, state): self.__state = state self.http = _FriendlyHttpAttributeErrorHelper() @property def shard_count(self): return self.__state.shard_count @property def user(self): return self.__state.user @property def self_id(self): return self.__state.user.id @property def member_cache_flags(self): return self.__state.member_cache_flags def store_emoji(self, guild, packet): return None def _get_voice_client(self, id): return None def _get_message(self, id): return None def _get_guild(self, id): return self.__state._get_guild(id) async def query_members(self, **kwargs: Any): return [] def __getattr__(self, attr): raise AttributeError(f'PartialTemplateState does not support {attr!r}.') class Template: """Represents a Discord template. .. versionadded:: 1.4 Attributes ----------- code: :class:`str` The template code. uses: :class:`int` How many times the template has been used. name: :class:`str` The name of the template. description: :class:`str` The description of the template. creator: :class:`User` The creator of the template. created_at: :class:`datetime.datetime` An aware datetime in UTC representing when the template was created. updated_at: :class:`datetime.datetime` An aware datetime in UTC representing when the template was last updated. This is referred to as "last synced" in the official Discord client. source_guild: :class:`Guild` The source guild. is_dirty: Optional[:class:`bool`] Whether the template has unsynced changes. .. versionadded:: 2.0 """ __slots__ = ( 'code', 'uses', 'name', 'description', 'creator', 'created_at', 'updated_at', 'source_guild', 'is_dirty', '_state', ) def __init__(self, *, state: ConnectionState, data: TemplatePayload) -> None: self._state = state self._store(data) def _store(self, data: TemplatePayload) -> None: self.code: str = data['code'] self.uses: int = data['usage_count'] self.name: str = data['name'] self.description: Optional[str] = data['description'] creator_data = data.get('creator') self.creator: Optional[User] = None if creator_data is None else self._state.create_user(creator_data) self.created_at: Optional[datetime.datetime] = parse_time(data.get('created_at')) self.updated_at: Optional[datetime.datetime] = parse_time(data.get('updated_at')) guild_id = int(data['source_guild_id']) guild: Optional[Guild] = self._state._get_guild(guild_id) self.source_guild: Guild if guild is None: source_serialised = data['serialized_source_guild'] source_serialised['id'] = guild_id state = _PartialTemplateState(state=self._state) # Guild expects a ConnectionState, we're passing a _PartialTemplateState self.source_guild = Guild(data=source_serialised, state=state) # type: ignore else: self.source_guild = guild self.is_dirty: Optional[bool] = data.get('is_dirty', None) def __repr__(self) -> str: return ( f'<Template code={self.code!r} uses={self.uses} name={self.name!r}' f' creator={self.creator!r} source_guild={self.source_guild!r} is_dirty={self.is_dirty}>' ) async def create_guild(self, name: str, region: Optional[VoiceRegion] = None, icon: Any = None) -> Guild: """|coro| Creates a :class:`.Guild` using the template. Bot accounts in more than 10 guilds are not allowed to create guilds. Parameters ---------- name: :class:`str` The name of the guild. region: :class:`.VoiceRegion` The region for the voice communication server. Defaults to :attr:`.VoiceRegion.us_west`. icon: :class:`bytes` The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit` for more details on what is expected. Raises ------ HTTPException Guild creation failed. InvalidArgument Invalid icon image format given. Must be PNG or JPG. Returns ------- :class:`.Guild` The guild created. This is not the same guild that is added to cache. """ if icon is not None: icon = _bytes_to_base64_data(icon) region = region or VoiceRegion.us_west region_value = region.value data = await self._state.http.create_from_template(self.code, name, region_value, icon) return Guild(data=data, state=self._state) async def sync(self) -> Template: """|coro| Sync the template to the guild's current state. You must have the :attr:`~Permissions.manage_guild` permission in the source guild to do this. .. versionadded:: 1.7 .. versionchanged:: 2.0 The template is no longer edited in-place, instead it is returned. Raises ------- HTTPException Editing the template failed. Forbidden You don't have permissions to edit the template. NotFound This template does not exist. Returns -------- :class:`Template` The newly edited template. """ data = await self._state.http.sync_template(self.source_guild.id, self.code) return Template(state=self._state, data=data) async def edit( self, *, name: str = MISSING, description: Optional[str] = MISSING, ) -> Template: """|coro| Edit the template metadata. You must have the :attr:`~Permissions.manage_guild` permission in the source guild to do this. .. versionadded:: 1.7 .. versionchanged:: 2.0 The template is no longer edited in-place, instead it is returned. Parameters ------------ name: :class:`str` The template's new name. description: Optional[:class:`str`] The template's new description. Raises ------- HTTPException Editing the template failed. Forbidden You don't have permissions to edit the template. NotFound This template does not exist. Returns -------- :class:`Template` The newly edited template. """ payload = {} if name is not MISSING: payload['name'] = name if description is not MISSING: payload['description'] = description data = await self._state.http.edit_template(self.source_guild.id, self.code, payload) return Template(state=self._state, data=data) async def delete(self) -> None: """|coro| Delete the template. You must have the :attr:`~Permissions.manage_guild` permission in the source guild to do this. .. versionadded:: 1.7 Raises ------- HTTPException Editing the template failed. Forbidden You don't have permissions to edit the template. NotFound This template does not exist. """ await self._state.http.delete_template(self.source_guild.id, self.code) @property def url(self) -> str: """:class:`str`: The template url. .. versionadded:: 2.0 """ return f'https://discord.new/{self.code}'
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/template.py
template.py
from __future__ import annotations import asyncio from collections import deque, OrderedDict import copy import datetime import itertools import logging from typing import Dict, Optional, TYPE_CHECKING, Union, Callable, Any, List, TypeVar, Coroutine, Sequence, Tuple, Deque import inspect import os from .guild import Guild from .activity import BaseActivity from .user import User, ClientUser from .emoji import Emoji from .mentions import AllowedMentions from .partial_emoji import PartialEmoji from .message import Message from .channel import * from .channel import _channel_factory from .raw_models import * from .member import Member from .role import Role from .enums import ChannelType, try_enum, Status from . import utils from .flags import ApplicationFlags, Intents, MemberCacheFlags from .object import Object from .invite import Invite from .integrations import _integration_factory from .interactions import Interaction from .ui.view import ViewStore, View from .stage_instance import StageInstance from .threads import Thread, ThreadMember from .sticker import GuildSticker if TYPE_CHECKING: from .abc import PrivateChannel from .message import MessageableChannel from .guild import GuildChannel, VocalGuildChannel from .http import HTTPClient from .voice_client import VoiceProtocol from .client import Client from .gateway import DiscordWebSocket from .types.activity import Activity as ActivityPayload from .types.channel import DMChannel as DMChannelPayload from .types.user import User as UserPayload from .types.emoji import Emoji as EmojiPayload from .types.sticker import GuildSticker as GuildStickerPayload from .types.guild import Guild as GuildPayload from .types.message import Message as MessagePayload T = TypeVar('T') CS = TypeVar('CS', bound='ConnectionState') Channel = Union[GuildChannel, VocalGuildChannel, PrivateChannel, PartialMessageable] class ChunkRequest: def __init__( self, guild_id: int, loop: asyncio.AbstractEventLoop, resolver: Callable[[int], Any], *, cache: bool = True, ) -> None: self.guild_id: int = guild_id self.resolver: Callable[[int], Any] = resolver self.loop: asyncio.AbstractEventLoop = loop self.cache: bool = cache self.nonce: str = os.urandom(16).hex() self.buffer: List[Member] = [] self.waiters: List[asyncio.Future[List[Member]]] = [] def add_members(self, members: List[Member]) -> None: self.buffer.extend(members) if self.cache: guild = self.resolver(self.guild_id) if guild is None: return for member in members: existing = guild.get_member(member.id) if existing is None or existing.joined_at is None: guild._add_member(member) async def wait(self) -> List[Member]: future = self.loop.create_future() self.waiters.append(future) try: return await future finally: self.waiters.remove(future) def get_future(self) -> asyncio.Future[List[Member]]: future = self.loop.create_future() self.waiters.append(future) return future def done(self) -> None: for future in self.waiters: if not future.done(): future.set_result(self.buffer) _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) 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, **options: Any, ) -> None: self.loop: asyncio.AbstractEventLoop = loop self.http: HTTPClient = http self.max_messages: Optional[int] = options.get('max_messages', 1000) 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] = utils._get_as_snowflake(options, 'application_id') self.heartbeat_timeout: float = options.get('heartbeat_timeout', 60.0) self.guild_ready_timeout: float = options.get('guild_ready_timeout', 2.0) if self.guild_ready_timeout < 0: raise ValueError('guild_ready_timeout cannot be negative') allowed_mentions = options.get('allowed_mentions') 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] = {} activity = options.get('activity', None) if activity: if not isinstance(activity, BaseActivity): raise TypeError('activity parameter must derive from BaseActivity.') activity = activity.to_dict() status = options.get('status', None) if status: if status is Status.offline: status = 'invisible' else: status = str(status) intents = options.get('intents', None) if intents is not None: if not isinstance(intents, Intents): raise TypeError(f'intents parameter must be Intent not {type(intents)!r}') else: intents = Intents.default() if not intents.guilds: _log.warning('Guilds intent seems to be disabled. This may cause state related issues.') self._chunk_guilds: bool = options.get('chunk_guilds_at_startup', intents.members) # 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.') cache_flags = options.get('member_cache_flags', None) if cache_flags is None: cache_flags = MemberCacheFlags.from_intents(intents) else: if not isinstance(cache_flags, MemberCacheFlags): raise TypeError(f'member_cache_flags parameter must be MemberCacheFlags not {type(cache_flags)!r}') cache_flags._verify_intents(intents) self.member_cache_flags: MemberCacheFlags = cache_flags self._activity: Optional[ActivityPayload] = activity self._status: Optional[str] = status self._intents: Intents = intents if not intents.members or cache_flags._empty: self.store_user = self.create_user # type: ignore self.deref_user = self.deref_user_no_intents # type: ignore 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) -> 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 discernable 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] = {} if views: self._view_store: ViewStore = ViewStore(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) @property def self_id(self) -> Optional[int]: u = self.user return u.id if u else None @property def intents(self) -> Intents: ret = Intents.none() ret.value = self._intents.value return ret @property 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: 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 prevent_view_updates_for(self, message_id: int) -> Optional[View]: return self._view_store.remove_message_tracking(message_id) @property def persistent_views(self) -> Sequence[View]: return self._view_store.persistent_views @property 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 @property def emojis(self) -> List[Emoji]: return list(self._emojis.values()) @property 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 @property 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 = DMChannel._from_message(self, channel_id) guild = None else: channel = guild and guild._resolve_channel(channel_id) return channel or PartialMessageable(state=self, id=channel_id), guild 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: str, limit: int, user_ids: List[int], cache: bool, presences: bool): guild_id = guild.id ws = self._get_websocket(guild_id) if ws is None: 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)) else: if 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 try: del self._ready_state except AttributeError: pass # already been deleted somehow 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']) # type: ignore 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 or Thread if channel and channel.__class__ in (TextChannel, Thread): 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 = Interaction(data=data, state=self) 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) 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, ch_type = _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: 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) # type: ignore 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) try: guild._member_count += 1 except AttributeError: pass 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: try: guild._member_count -= 1 except AttributeError: pass user_id = int(data['user']['id']) member = guild.get_member(user_id) if member is not None: guild._remove_member(member) # type: ignore self.dispatch('member_remove', member) else: _log.debug('GUILD_MEMBER_REMOVE referencing an unknown guild ID: %s. Discarding.', data['guild_id']) 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 won't be None here guild.emojis = tuple(map(lambda d: self.store_emoji(guild, d), data['emojis'])) # type: ignore 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 won't be None here guild.stickers = tuple(map(lambda d: self.store_sticker(guild, d), data['stickers'])) # type: ignore 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=True, cache=None): cache = cache or 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): 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): asyncio.create_task(self._chunk_and_dispatch(guild, unavailable)) 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) asyncio.create_task(logging_coroutine(coro, info='Voice Protocol voice state update handler')) member, before, after = guild._update_voice_state(data, channel_id) # type: ignore 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) # type: ignore 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) asyncio.create_task(logging_coroutine(coro, info='Voice Protocol voice server update handler')) def parse_typing_start(self, data) -> None: channel, guild = self._get_guild_channel(data) if channel is not None: member = None user_id = utils._get_as_snowflake(data, 'user_id') if isinstance(channel, DMChannel): member = channel.recipient elif isinstance(channel, (Thread, TextChannel)) and guild is not None: # user_id won't be None member = guild.get_member(user_id) # type: ignore if member is None: member_data = data.get('member') if member_data: member = Member(data=member_data, state=self, guild=guild) elif isinstance(channel, GroupChannel): member = utils.find(lambda x: x.id == user_id, channel.recipients) if member is not None: timestamp = datetime.datetime.fromtimestamp(data.get('timestamp'), tz=datetime.timezone.utc) self.dispatch('typing', channel, member, timestamp) 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 def create_message( self, *, channel: Union[TextChannel, Thread, DMChannel, GroupChannel, PartialMessageable], data: MessagePayload ) -> Message: return Message(state=self, channel=channel, data=data) class AutoShardedConnectionState(ConnectionState): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.shard_ids: Union[List[int], range] = [] self.shards_launched: asyncio.Event = asyncio.Event() def _update_message_references(self) -> None: # self._messages won't be None when this is called for msg in self._messages: # type: ignore if not msg.guild: continue new_guild = self._get_guild(msg.guild.id) if new_guild is not None and new_guild is not msg.guild: channel_id = msg.channel.id channel = new_guild._resolve_channel(channel_id) or Object(id=channel_id) # channel will either be a TextChannel, Thread or Object msg._rebind_cached_references(new_guild, channel) # type: ignore async def chunker( self, guild_id: int, query: str = '', limit: int = 0, presences: bool = False, *, shard_id: Optional[int] = None, nonce: Optional[str] = None, ) -> None: ws = self._get_websocket(guild_id, shard_id=shard_id) await ws.request_chunks(guild_id, query=query, limit=limit, presences=presences, nonce=nonce) async def _delay_ready(self) -> None: await self.shards_launched.wait() processed = [] max_concurrency = len(self.shard_ids) * 2 current_bucket = [] 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): _log.debug('Guild ID %d requires chunking, will be done in the background.', guild.id) if len(current_bucket) >= max_concurrency: try: await utils.sane_wait_for(current_bucket, timeout=max_concurrency * 70.0) except asyncio.TimeoutError: fmt = 'Shard ID %s failed to wait for chunks from a sub-bucket with length %d' _log.warning(fmt, guild.shard_id, len(current_bucket)) finally: current_bucket = [] # Chunk the guild in the background while we wait for GUILD_CREATE streaming future = asyncio.ensure_future(self.chunk_guild(guild)) current_bucket.append(future) else: future = self.loop.create_future() future.set_result([]) processed.append((guild, future)) guilds = sorted(processed, key=lambda g: g[0].shard_id) for shard_id, info in itertools.groupby(guilds, key=lambda g: g[0].shard_id): children, futures = zip(*info) # 110 reqs/minute w/ 1 req/guild plus some buffer timeout = 61 * (len(children) / 110) try: await utils.sane_wait_for(futures, timeout=timeout) except asyncio.TimeoutError: _log.warning( 'Shard ID %s failed to wait for chunks (timeout=%.2f) for %d guilds', shard_id, timeout, len(guilds) ) for guild in children: if guild.unavailable is False: self.dispatch('guild_available', guild) else: self.dispatch('guild_join', guild) self.dispatch('shard_ready', shard_id) # remove the state try: del self._ready_state except AttributeError: pass # already been deleted somehow # regular users cannot shard so we won't worry about it here. # clear the current task self._ready_task = None # dispatch the event self.call_handlers('ready') self.dispatch('ready') def parse_ready(self, data) -> None: if not hasattr(self, '_ready_state'): self._ready_state = asyncio.Queue() self.user = user = ClientUser(state=self, data=data['user']) # self._users is a list of Users, we're setting a ClientUser self._users[user.id] = user # type: ignore if self.application_id is None: try: application = data['application'] except KeyError: pass else: self.application_id = utils._get_as_snowflake(application, 'id') self.application_flags = ApplicationFlags._from_value(application['flags']) for guild_data in data['guilds']: self._add_guild_from_data(guild_data) if self._messages: self._update_message_references() self.dispatch('connect') self.dispatch('shard_connect', data['__shard_id__']) if self._ready_task is None: self._ready_task = asyncio.create_task(self._delay_ready()) def parse_resumed(self, data) -> None: self.dispatch('resumed') self.dispatch('shard_resumed', data['__shard_id__'])
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/state.py
state.py
from __future__ import annotations import asyncio import logging import aiohttp from .state import AutoShardedConnectionState from .client import Client from .backoff import ExponentialBackoff from .gateway import * from .errors import ( ClientException, HTTPException, GatewayNotFound, ConnectionClosed, PrivilegedIntentsRequired, ) from .enums import Status from typing import TYPE_CHECKING, Any, Callable, Tuple, Type, Optional, List, Dict, TypeVar if TYPE_CHECKING: from .gateway import DiscordWebSocket from .activity import BaseActivity from .enums import Status EI = TypeVar('EI', bound='EventItem') __all__ = ( 'AutoShardedClient', 'ShardInfo', ) _log = logging.getLogger(__name__) class EventType: close = 0 reconnect = 1 resume = 2 identify = 3 terminate = 4 clean_close = 5 class EventItem: __slots__ = ('type', 'shard', 'error') def __init__(self, etype: int, shard: Optional['Shard'], error: Optional[Exception]) -> None: self.type: int = etype self.shard: Optional['Shard'] = shard self.error: Optional[Exception] = error def __lt__(self: EI, other: EI) -> bool: if not isinstance(other, EventItem): return NotImplemented return self.type < other.type def __eq__(self: EI, other: EI) -> bool: if not isinstance(other, EventItem): return NotImplemented return self.type == other.type def __hash__(self) -> int: return hash(self.type) class Shard: def __init__(self, ws: DiscordWebSocket, client: AutoShardedClient, queue_put: Callable[[EventItem], None]) -> None: self.ws: DiscordWebSocket = ws self._client: Client = client self._dispatch: Callable[..., None] = client.dispatch self._queue_put: Callable[[EventItem], None] = queue_put self.loop: asyncio.AbstractEventLoop = self._client.loop self._disconnect: bool = False self._reconnect = client._reconnect self._backoff: ExponentialBackoff = ExponentialBackoff() self._task: Optional[asyncio.Task] = None self._handled_exceptions: Tuple[Type[Exception], ...] = ( OSError, HTTPException, GatewayNotFound, ConnectionClosed, aiohttp.ClientError, asyncio.TimeoutError, ) @property def id(self) -> int: # DiscordWebSocket.shard_id is set in the from_client classmethod return self.ws.shard_id # type: ignore def launch(self) -> None: self._task = self.loop.create_task(self.worker()) def _cancel_task(self) -> None: if self._task is not None and not self._task.done(): self._task.cancel() async def close(self) -> None: self._cancel_task() await self.ws.close(code=1000) async def disconnect(self) -> None: await self.close() self._dispatch('shard_disconnect', self.id) async def _handle_disconnect(self, e: Exception) -> None: self._dispatch('disconnect') self._dispatch('shard_disconnect', self.id) if not self._reconnect: self._queue_put(EventItem(EventType.close, self, e)) return if self._client.is_closed(): return if isinstance(e, OSError) and e.errno in (54, 10054): # If we get Connection reset by peer then always try to RESUME the connection. exc = ReconnectWebSocket(self.id, resume=True) self._queue_put(EventItem(EventType.resume, self, exc)) return if isinstance(e, ConnectionClosed): if e.code == 4014: self._queue_put(EventItem(EventType.terminate, self, PrivilegedIntentsRequired(self.id))) return if e.code != 1000: self._queue_put(EventItem(EventType.close, self, e)) return retry = self._backoff.delay() _log.error('Attempting a reconnect for shard ID %s in %.2fs', self.id, retry, exc_info=e) await asyncio.sleep(retry) self._queue_put(EventItem(EventType.reconnect, self, e)) async def worker(self) -> None: while not self._client.is_closed(): try: await self.ws.poll_event() except ReconnectWebSocket as e: etype = EventType.resume if e.resume else EventType.identify self._queue_put(EventItem(etype, self, e)) break except self._handled_exceptions as e: await self._handle_disconnect(e) break except asyncio.CancelledError: break except Exception as e: self._queue_put(EventItem(EventType.terminate, self, e)) break async def reidentify(self, exc: ReconnectWebSocket) -> None: self._cancel_task() self._dispatch('disconnect') self._dispatch('shard_disconnect', self.id) _log.info('Got a request to %s the websocket at Shard ID %s.', exc.op, self.id) try: coro = DiscordWebSocket.from_client( self._client, resume=exc.resume, shard_id=self.id, session=self.ws.session_id, sequence=self.ws.sequence, ) self.ws = await asyncio.wait_for(coro, timeout=60.0) except self._handled_exceptions as e: await self._handle_disconnect(e) except asyncio.CancelledError: return except Exception as e: self._queue_put(EventItem(EventType.terminate, self, e)) else: self.launch() async def reconnect(self) -> None: self._cancel_task() try: coro = DiscordWebSocket.from_client(self._client, shard_id=self.id) self.ws = await asyncio.wait_for(coro, timeout=60.0) except self._handled_exceptions as e: await self._handle_disconnect(e) except asyncio.CancelledError: return except Exception as e: self._queue_put(EventItem(EventType.terminate, self, e)) else: self.launch() class ShardInfo: """A class that gives information and control over a specific shard. You can retrieve this object via :meth:`AutoShardedClient.get_shard` or :attr:`AutoShardedClient.shards`. .. versionadded:: 1.4 Attributes ------------ id: :class:`int` The shard ID for this shard. shard_count: Optional[:class:`int`] The shard count for this cluster. If this is ``None`` then the bot has not started yet. """ __slots__ = ('_parent', 'id', 'shard_count') def __init__(self, parent: Shard, shard_count: Optional[int]) -> None: self._parent: Shard = parent self.id: int = parent.id self.shard_count: Optional[int] = shard_count def is_closed(self) -> bool: """:class:`bool`: Whether the shard connection is currently closed.""" return not self._parent.ws.open async def disconnect(self) -> None: """|coro| Disconnects a shard. When this is called, the shard connection will no longer be open. If the shard is already disconnected this does nothing. """ if self.is_closed(): return await self._parent.disconnect() async def reconnect(self) -> None: """|coro| Disconnects and then connects the shard again. """ if not self.is_closed(): await self._parent.disconnect() await self._parent.reconnect() async def connect(self) -> None: """|coro| Connects a shard. If the shard is already connected this does nothing. """ if not self.is_closed(): return await self._parent.reconnect() @property def latency(self) -> float: """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds for this shard.""" return self._parent.ws.latency def is_ws_ratelimited(self) -> bool: """:class:`bool`: Whether the websocket is currently rate limited. This can be useful to know when deciding whether you should query members using HTTP or via the gateway. .. versionadded:: 1.6 """ return self._parent.ws.is_ratelimited() class AutoShardedClient(Client): """A client similar to :class:`Client` except it handles the complications of sharding for the user into a more manageable and transparent single process bot. When using this client, you will be able to use it as-if it was a regular :class:`Client` with a single shard when implementation wise internally it is split up into multiple shards. This allows you to not have to deal with IPC or other complicated infrastructure. It is recommended to use this client only if you have surpassed at least 1000 guilds. If no :attr:`.shard_count` is provided, then the library will use the Bot Gateway endpoint call to figure out how many shards to use. If a ``shard_ids`` parameter is given, then those shard IDs will be used to launch the internal shards. Note that :attr:`.shard_count` must be provided if this is used. By default, when omitted, the client will launch shards from 0 to ``shard_count - 1``. Attributes ------------ shard_ids: Optional[List[:class:`int`]] An optional list of shard_ids to launch the shards with. """ if TYPE_CHECKING: _connection: AutoShardedConnectionState def __init__(self, *args: Any, loop: Optional[asyncio.AbstractEventLoop] = None, **kwargs: Any) -> None: kwargs.pop('shard_id', None) self.shard_ids: Optional[List[int]] = kwargs.pop('shard_ids', None) super().__init__(*args, loop=loop, **kwargs) if self.shard_ids is not None: if self.shard_count is None: raise ClientException('When passing manual shard_ids, you must provide a shard_count.') elif not isinstance(self.shard_ids, (list, tuple)): raise ClientException('shard_ids parameter must be a list or a tuple.') # instead of a single websocket, we have multiple # the key is the shard_id self.__shards = {} self._connection._get_websocket = self._get_websocket self._connection._get_client = lambda: self self.__queue = asyncio.PriorityQueue() def _get_websocket(self, guild_id: Optional[int] = None, *, shard_id: Optional[int] = None) -> DiscordWebSocket: if shard_id is None: # guild_id won't be None if shard_id is None and shard_count won't be None here shard_id = (guild_id >> 22) % self.shard_count # type: ignore return self.__shards[shard_id].ws def _get_state(self, **options: Any) -> AutoShardedConnectionState: return AutoShardedConnectionState( dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, loop=self.loop, **options, ) @property def latency(self) -> float: """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This operates similarly to :meth:`Client.latency` except it uses the average latency of every shard's latency. To get a list of shard latency, check the :attr:`latencies` property. Returns ``nan`` if there are no shards ready. """ if not self.__shards: return float('nan') return sum(latency for _, latency in self.latencies) / len(self.__shards) @property def latencies(self) -> List[Tuple[int, float]]: """List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This returns a list of tuples with elements ``(shard_id, latency)``. """ return [(shard_id, shard.ws.latency) for shard_id, shard in self.__shards.items()] def get_shard(self, shard_id: int) -> Optional[ShardInfo]: """Optional[:class:`ShardInfo`]: Gets the shard information at a given shard ID or ``None`` if not found.""" try: parent = self.__shards[shard_id] except KeyError: return None else: return ShardInfo(parent, self.shard_count) @property def shards(self) -> Dict[int, ShardInfo]: """Mapping[int, :class:`ShardInfo`]: Returns a mapping of shard IDs to their respective info object.""" return {shard_id: ShardInfo(parent, self.shard_count) for shard_id, parent in self.__shards.items()} async def launch_shard(self, gateway: str, shard_id: int, *, initial: bool = False) -> None: try: coro = DiscordWebSocket.from_client(self, initial=initial, gateway=gateway, shard_id=shard_id) ws = await asyncio.wait_for(coro, timeout=180.0) except Exception: _log.exception('Failed to connect for shard_id: %s. Retrying...', shard_id) await asyncio.sleep(5.0) return await self.launch_shard(gateway, shard_id) # keep reading the shard while others connect self.__shards[shard_id] = ret = Shard(ws, self, self.__queue.put_nowait) ret.launch() async def launch_shards(self) -> None: if self.shard_count is None: self.shard_count, gateway = await self.http.get_bot_gateway() else: gateway = await self.http.get_gateway() self._connection.shard_count = self.shard_count shard_ids = self.shard_ids or range(self.shard_count) self._connection.shard_ids = shard_ids for shard_id in shard_ids: initial = shard_id == shard_ids[0] await self.launch_shard(gateway, shard_id, initial=initial) self._connection.shards_launched.set() async def connect(self, *, reconnect: bool = True) -> None: self._reconnect = reconnect await self.launch_shards() while not self.is_closed(): item = await self.__queue.get() if item.type == EventType.close: await self.close() if isinstance(item.error, ConnectionClosed): if item.error.code != 1000: raise item.error if item.error.code == 4014: raise PrivilegedIntentsRequired(item.shard.id) from None return elif item.type in (EventType.identify, EventType.resume): await item.shard.reidentify(item.error) elif item.type == EventType.reconnect: await item.shard.reconnect() elif item.type == EventType.terminate: await self.close() raise item.error elif item.type == EventType.clean_close: return async def close(self) -> None: """|coro| Closes the connection to Discord. """ if self.is_closed(): return self._closed = True for vc in self.voice_clients: try: await vc.disconnect(force=True) except Exception: pass to_close = [asyncio.ensure_future(shard.close(), loop=self.loop) for shard in self.__shards.values()] if to_close: await asyncio.wait(to_close) await self.http.close() self.__queue.put_nowait(EventItem(EventType.clean_close, None, None)) async def change_presence( self, *, activity: Optional[BaseActivity] = None, status: Optional[Status] = None, shard_id: int = None, ) -> None: """|coro| Changes the client's presence. Example: :: game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) .. versionchanged:: 2.0 Removed the ``afk`` keyword-only parameter. Parameters ---------- activity: Optional[:class:`BaseActivity`] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`Status`] Indicates what status to change to. If ``None``, then :attr:`Status.online` is used. shard_id: Optional[:class:`int`] The shard_id to change the presence to. If not specified or ``None``, then it will change the presence of every shard the bot can see. Raises ------ InvalidArgument If the ``activity`` parameter is not of proper type. """ if status is None: status_value = 'online' status_enum = Status.online elif status is Status.offline: status_value = 'invisible' status_enum = Status.offline else: status_enum = status status_value = str(status) if shard_id is None: for shard in self.__shards.values(): await shard.ws.change_presence(activity=activity, status=status_value) guilds = self._connection.guilds else: shard = self.__shards[shard_id] await shard.ws.change_presence(activity=activity, status=status_value) guilds = [g for g in self._connection.guilds if g.shard_id == shard_id] activities = () if activity is None else (activity,) for guild in guilds: me = guild.me if me is None: continue # Member.activities is typehinted as Tuple[ActivityType, ...], we may be setting it as Tuple[BaseActivity, ...] me.activities = activities # type: ignore me.status = status_enum def is_ws_ratelimited(self) -> bool: """:class:`bool`: Whether the websocket is currently rate limited. This can be useful to know when deciding whether you should query members using HTTP or via the gateway. This implementation checks if any of the shards are rate limited. For more granular control, consider :meth:`ShardInfo.is_ws_ratelimited`. .. versionadded:: 1.6 """ return any(shard.ws.is_ratelimited() for shard in self.__shards.values())
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/shard.py
shard.py
from __future__ import annotations from typing import Any, Callable, ClassVar, Dict, Generic, Iterator, List, Optional, Tuple, Type, TypeVar, overload from .enums import UserFlags __all__ = ( 'SystemChannelFlags', 'MessageFlags', 'PublicUserFlags', 'Intents', 'MemberCacheFlags', 'ApplicationFlags', ) FV = TypeVar('FV', bound='flag_value') BF = TypeVar('BF', bound='BaseFlags') class flag_value: def __init__(self, func: Callable[[Any], int]): self.flag = func(None) self.__doc__ = func.__doc__ @overload def __get__(self: FV, instance: None, owner: Type[BF]) -> FV: ... @overload 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: BF, value: bool) -> None: instance._set_flag(self.flag, value) def __repr__(self): return f'<flag_value flag={self.flag!r}>' class alias_flag_value(flag_value): pass def fill_with_flags(*, inverted: bool = False): def decorator(cls: Type[BF]): # fmt: off cls.VALID_FLAGS = { name: value.flag for name, value in cls.__dict__.items() if isinstance(value, flag_value) } # fmt: on 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 # n.b. flags must inherit from this and use the decorator above class BaseFlags: VALID_FLAGS: ClassVar[Dict[str, int]] DEFAULT_VALUE: ClassVar[int] value: int __slots__ = ('value',) def __init__(self, **kwargs: bool): self.value = self.DEFAULT_VALUE for key, value in kwargs.items(): if key not in self.VALID_FLAGS: raise TypeError(f'{key!r} is not a valid flag name.') setattr(self, key, value) @classmethod def _from_value(cls, value): self = cls.__new__(cls) self.value = value return self def __eq__(self, other: Any) -> bool: return isinstance(other, self.__class__) and self.value == other.value def __ne__(self, other: Any) -> bool: return not self.__eq__(other) def __hash__(self) -> int: return hash(self.value) def __repr__(self) -> str: return f'<{self.__class__.__name__} value={self.value}>' def __iter__(self) -> Iterator[Tuple[str, bool]]: for name, value in self.__class__.__dict__.items(): if isinstance(value, alias_flag_value): continue if isinstance(value, flag_value): yield (name, self._has_flag(value.flag)) def _has_flag(self, o: int) -> bool: return (self.value & o) == o def _set_flag(self, o: int, toggle: bool) -> None: if toggle is True: self.value |= o elif toggle is False: self.value &= ~o else: raise TypeError(f'Value to set for {self.__class__.__name__} must be a bool.') @fill_with_flags(inverted=True) class SystemChannelFlags(BaseFlags): r"""Wraps up a Discord system channel flag value. Similar to :class:`Permissions`\, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit the system flags easily. To construct an object you can pass keyword arguments denoting the flags to enable or disable. .. container:: operations .. describe:: x == y Checks if two flags are equal. .. describe:: x != y Checks if two flags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Attributes ----------- value: :class:`int` The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value. """ __slots__ = () # For some reason the flags for system channels are "inverted" # ergo, if they're set then it means "suppress" (off in the GUI toggle) # Since this is counter-intuitive from an API perspective and annoying # these will be inverted automatically def _has_flag(self, o: int) -> bool: return (self.value & o) != o def _set_flag(self, o: int, toggle: bool) -> None: if toggle is True: self.value &= ~o elif toggle is False: self.value |= o else: raise TypeError('Value to set for SystemChannelFlags must be a bool.') @flag_value def join_notifications(self): """:class:`bool`: Returns ``True`` if the system channel is used for member join notifications.""" return 1 @flag_value def premium_subscriptions(self): """:class:`bool`: Returns ``True`` if the system channel is used for "Nitro boosting" notifications.""" return 2 @flag_value def guild_reminder_notifications(self): """:class:`bool`: Returns ``True`` if the system channel is used for server setup helpful tips notifications. .. versionadded:: 2.0 """ return 4 @fill_with_flags() class MessageFlags(BaseFlags): r"""Wraps up a Discord Message flag value. See :class:`SystemChannelFlags`. .. container:: operations .. describe:: x == y Checks if two flags are equal. .. describe:: x != y Checks if two flags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. .. versionadded:: 1.3 Attributes ----------- value: :class:`int` The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value. """ __slots__ = () @flag_value def crossposted(self): """:class:`bool`: Returns ``True`` if the message is the original crossposted message.""" return 1 @flag_value def is_crossposted(self): """:class:`bool`: Returns ``True`` if the message was crossposted from another channel.""" return 2 @flag_value def suppress_embeds(self): """:class:`bool`: Returns ``True`` if the message's embeds have been suppressed.""" return 4 @flag_value def source_message_deleted(self): """:class:`bool`: Returns ``True`` if the source message for this crosspost has been deleted.""" return 8 @flag_value def urgent(self): """:class:`bool`: Returns ``True`` if the source message is an urgent message. An urgent message is one sent by Discord Trust and Safety. """ return 16 @flag_value def has_thread(self): """:class:`bool`: Returns ``True`` if the source message is associated with a thread. .. versionadded:: 2.0 """ return 32 @flag_value def ephemeral(self): """:class:`bool`: Returns ``True`` if the source message is ephemeral. .. versionadded:: 2.0 """ return 64 @fill_with_flags() class PublicUserFlags(BaseFlags): r"""Wraps up the Discord User Public flags. .. container:: operations .. describe:: x == y Checks if two PublicUserFlags are equal. .. describe:: x != y Checks if two PublicUserFlags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown. .. versionadded:: 1.4 Attributes ----------- value: :class:`int` The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value. """ __slots__ = () @flag_value def staff(self): """:class:`bool`: Returns ``True`` if the user is a Discord Employee.""" return UserFlags.staff.value @flag_value def partner(self): """:class:`bool`: Returns ``True`` if the user is a Discord Partner.""" return UserFlags.partner.value @flag_value def hypesquad(self): """:class:`bool`: Returns ``True`` if the user is a HypeSquad Events member.""" return UserFlags.hypesquad.value @flag_value def bug_hunter(self): """:class:`bool`: Returns ``True`` if the user is a Bug Hunter""" return UserFlags.bug_hunter.value @flag_value def hypesquad_bravery(self): """:class:`bool`: Returns ``True`` if the user is a HypeSquad Bravery member.""" return UserFlags.hypesquad_bravery.value @flag_value def hypesquad_brilliance(self): """:class:`bool`: Returns ``True`` if the user is a HypeSquad Brilliance member.""" return UserFlags.hypesquad_brilliance.value @flag_value def hypesquad_balance(self): """:class:`bool`: Returns ``True`` if the user is a HypeSquad Balance member.""" return UserFlags.hypesquad_balance.value @flag_value def early_supporter(self): """:class:`bool`: Returns ``True`` if the user is an Early Supporter.""" return UserFlags.early_supporter.value @flag_value def team_user(self): """:class:`bool`: Returns ``True`` if the user is a Team User.""" return UserFlags.team_user.value @flag_value def system(self): """:class:`bool`: Returns ``True`` if the user is a system user (i.e. represents Discord officially).""" return UserFlags.system.value @flag_value def bug_hunter_level_2(self): """:class:`bool`: Returns ``True`` if the user is a Bug Hunter Level 2""" return UserFlags.bug_hunter_level_2.value @flag_value def verified_bot(self): """:class:`bool`: Returns ``True`` if the user is a Verified Bot.""" return UserFlags.verified_bot.value @flag_value def verified_bot_developer(self): """:class:`bool`: Returns ``True`` if the user is an Early Verified Bot Developer.""" return UserFlags.verified_bot_developer.value @alias_flag_value def early_verified_bot_developer(self): """:class:`bool`: An alias for :attr:`verified_bot_developer`. .. versionadded:: 1.5 """ return UserFlags.verified_bot_developer.value @flag_value def discord_certified_moderator(self): """:class:`bool`: Returns ``True`` if the user is a Discord Certified Moderator. .. versionadded:: 2.0 """ return UserFlags.discord_certified_moderator.value def all(self) -> List[UserFlags]: """List[:class:`UserFlags`]: Returns all public flags the user has.""" return [public_flag for public_flag in UserFlags if self._has_flag(public_flag.value)] @fill_with_flags() class Intents(BaseFlags): r"""Wraps up a Discord gateway intent flag. Similar to :class:`Permissions`\, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. To construct an object you can pass keyword arguments denoting the flags to enable or disable. This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the ``intents`` keyword argument of :class:`Client`. .. versionadded:: 1.5 .. container:: operations .. describe:: x == y Checks if two flags are equal. .. describe:: x != y Checks if two flags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Attributes ----------- value: :class:`int` The raw value. You should query flags via the properties rather than using this raw value. """ __slots__ = () def __init__(self, **kwargs: bool): self.value = self.DEFAULT_VALUE for key, value in kwargs.items(): if key not in self.VALID_FLAGS: raise TypeError(f'{key!r} is not a valid flag name.') setattr(self, key, value) @classmethod def all(cls: Type[Intents]) -> Intents: """A factory method that creates a :class:`Intents` with everything enabled.""" bits = max(cls.VALID_FLAGS.values()).bit_length() value = (1 << bits) - 1 self = cls.__new__(cls) self.value = value return self @classmethod def none(cls: Type[Intents]) -> Intents: """A factory method that creates a :class:`Intents` with everything disabled.""" self = cls.__new__(cls) self.value = self.DEFAULT_VALUE return self @classmethod def default(cls: Type[Intents]) -> Intents: """A factory method that creates a :class:`Intents` with everything enabled except :attr:`presences` and :attr:`members`. """ self = cls.all() self.presences = False self.members = False return self @flag_value def guilds(self): """:class:`bool`: Whether guild related events are enabled. This corresponds to the following events: - :func:`on_guild_join` - :func:`on_guild_remove` - :func:`on_guild_available` - :func:`on_guild_unavailable` - :func:`on_guild_channel_update` - :func:`on_guild_channel_create` - :func:`on_guild_channel_delete` - :func:`on_guild_channel_pins_update` This also corresponds to the following attributes and classes in terms of cache: - :attr:`Client.guilds` - :class:`Guild` and all its attributes. - :meth:`Client.get_channel` - :meth:`Client.get_all_channels` It is highly advisable to leave this intent enabled for your bot to function. """ return 1 << 0 @flag_value def members(self): """:class:`bool`: Whether guild member related events are enabled. This corresponds to the following events: - :func:`on_member_join` - :func:`on_member_remove` - :func:`on_member_update` - :func:`on_user_update` This also corresponds to the following attributes and classes in terms of cache: - :meth:`Client.get_all_members` - :meth:`Client.get_user` - :meth:`Guild.chunk` - :meth:`Guild.fetch_members` - :meth:`Guild.get_member` - :attr:`Guild.members` - :attr:`Member.roles` - :attr:`Member.nick` - :attr:`Member.premium_since` - :attr:`User.name` - :attr:`User.avatar` - :attr:`User.discriminator` For more information go to the :ref:`member intent documentation <need_members_intent>`. .. note:: Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification. """ return 1 << 1 @flag_value def bans(self): """:class:`bool`: Whether guild ban related events are enabled. This corresponds to the following events: - :func:`on_member_ban` - :func:`on_member_unban` This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 2 @flag_value def emojis(self): """:class:`bool`: Alias of :attr:`.emojis_and_stickers`. .. versionchanged:: 2.0 Changed to an alias. """ return 1 << 3 @alias_flag_value def emojis_and_stickers(self): """:class:`bool`: Whether guild emoji and sticker related events are enabled. .. versionadded:: 2.0 This corresponds to the following events: - :func:`on_guild_emojis_update` - :func:`on_guild_stickers_update` This also corresponds to the following attributes and classes in terms of cache: - :class:`Emoji` - :class:`GuildSticker` - :meth:`Client.get_emoji` - :meth:`Client.get_sticker` - :meth:`Client.emojis` - :meth:`Client.stickers` - :attr:`Guild.emojis` - :attr:`Guild.stickers` """ return 1 << 3 @flag_value def integrations(self): """:class:`bool`: Whether guild integration related events are enabled. This corresponds to the following events: - :func:`on_guild_integrations_update` - :func:`on_integration_create` - :func:`on_integration_update` - :func:`on_raw_integration_delete` This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 4 @flag_value def webhooks(self): """:class:`bool`: Whether guild webhook related events are enabled. This corresponds to the following events: - :func:`on_webhooks_update` This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 5 @flag_value def invites(self): """:class:`bool`: Whether guild invite related events are enabled. This corresponds to the following events: - :func:`on_invite_create` - :func:`on_invite_delete` This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 6 @flag_value def voice_states(self): """:class:`bool`: Whether guild voice state related events are enabled. This corresponds to the following events: - :func:`on_voice_state_update` This also corresponds to the following attributes and classes in terms of cache: - :attr:`VoiceChannel.members` - :attr:`VoiceChannel.voice_states` - :attr:`Member.voice` .. note:: This intent is required to connect to voice. """ return 1 << 7 @flag_value def presences(self): """:class:`bool`: Whether guild presence related events are enabled. This corresponds to the following events: - :func:`on_presence_update` This also corresponds to the following attributes and classes in terms of cache: - :attr:`Member.activities` - :attr:`Member.status` - :attr:`Member.raw_status` For more information go to the :ref:`presence intent documentation <need_presence_intent>`. .. note:: Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification. """ return 1 << 8 @alias_flag_value def messages(self): """:class:`bool`: Whether guild and direct message related events are enabled. This is a shortcut to set or get both :attr:`guild_messages` and :attr:`dm_messages`. This corresponds to the following events: - :func:`on_message` (both guilds and DMs) - :func:`on_message_edit` (both guilds and DMs) - :func:`on_message_delete` (both guilds and DMs) - :func:`on_raw_message_delete` (both guilds and DMs) - :func:`on_raw_message_edit` (both guilds and DMs) This also corresponds to the following attributes and classes in terms of cache: - :class:`Message` - :attr:`Client.cached_messages` Note that due to an implicit relationship this also corresponds to the following events: - :func:`on_reaction_add` (both guilds and DMs) - :func:`on_reaction_remove` (both guilds and DMs) - :func:`on_reaction_clear` (both guilds and DMs) """ return (1 << 9) | (1 << 12) @flag_value def guild_messages(self): """:class:`bool`: Whether guild message related events are enabled. See also :attr:`dm_messages` for DMs or :attr:`messages` for both. This corresponds to the following events: - :func:`on_message` (only for guilds) - :func:`on_message_edit` (only for guilds) - :func:`on_message_delete` (only for guilds) - :func:`on_raw_message_delete` (only for guilds) - :func:`on_raw_message_edit` (only for guilds) This also corresponds to the following attributes and classes in terms of cache: - :class:`Message` - :attr:`Client.cached_messages` (only for guilds) Note that due to an implicit relationship this also corresponds to the following events: - :func:`on_reaction_add` (only for guilds) - :func:`on_reaction_remove` (only for guilds) - :func:`on_reaction_clear` (only for guilds) """ return 1 << 9 @flag_value def dm_messages(self): """:class:`bool`: Whether direct message related events are enabled. See also :attr:`guild_messages` for guilds or :attr:`messages` for both. This corresponds to the following events: - :func:`on_message` (only for DMs) - :func:`on_message_edit` (only for DMs) - :func:`on_message_delete` (only for DMs) - :func:`on_raw_message_delete` (only for DMs) - :func:`on_raw_message_edit` (only for DMs) This also corresponds to the following attributes and classes in terms of cache: - :class:`Message` - :attr:`Client.cached_messages` (only for DMs) Note that due to an implicit relationship this also corresponds to the following events: - :func:`on_reaction_add` (only for DMs) - :func:`on_reaction_remove` (only for DMs) - :func:`on_reaction_clear` (only for DMs) """ return 1 << 12 @alias_flag_value def reactions(self): """:class:`bool`: Whether guild and direct message reaction related events are enabled. This is a shortcut to set or get both :attr:`guild_reactions` and :attr:`dm_reactions`. This corresponds to the following events: - :func:`on_reaction_add` (both guilds and DMs) - :func:`on_reaction_remove` (both guilds and DMs) - :func:`on_reaction_clear` (both guilds and DMs) - :func:`on_raw_reaction_add` (both guilds and DMs) - :func:`on_raw_reaction_remove` (both guilds and DMs) - :func:`on_raw_reaction_clear` (both guilds and DMs) This also corresponds to the following attributes and classes in terms of cache: - :attr:`Message.reactions` (both guild and DM messages) """ return (1 << 10) | (1 << 13) @flag_value def guild_reactions(self): """:class:`bool`: Whether guild message reaction related events are enabled. See also :attr:`dm_reactions` for DMs or :attr:`reactions` for both. This corresponds to the following events: - :func:`on_reaction_add` (only for guilds) - :func:`on_reaction_remove` (only for guilds) - :func:`on_reaction_clear` (only for guilds) - :func:`on_raw_reaction_add` (only for guilds) - :func:`on_raw_reaction_remove` (only for guilds) - :func:`on_raw_reaction_clear` (only for guilds) This also corresponds to the following attributes and classes in terms of cache: - :attr:`Message.reactions` (only for guild messages) """ return 1 << 10 @flag_value def dm_reactions(self): """:class:`bool`: Whether direct message reaction related events are enabled. See also :attr:`guild_reactions` for guilds or :attr:`reactions` for both. This corresponds to the following events: - :func:`on_reaction_add` (only for DMs) - :func:`on_reaction_remove` (only for DMs) - :func:`on_reaction_clear` (only for DMs) - :func:`on_raw_reaction_add` (only for DMs) - :func:`on_raw_reaction_remove` (only for DMs) - :func:`on_raw_reaction_clear` (only for DMs) This also corresponds to the following attributes and classes in terms of cache: - :attr:`Message.reactions` (only for DM messages) """ return 1 << 13 @alias_flag_value def typing(self): """:class:`bool`: Whether guild and direct message typing related events are enabled. This is a shortcut to set or get both :attr:`guild_typing` and :attr:`dm_typing`. This corresponds to the following events: - :func:`on_typing` (both guilds and DMs) This does not correspond to any attributes or classes in the library in terms of cache. """ return (1 << 11) | (1 << 14) @flag_value def guild_typing(self): """:class:`bool`: Whether guild and direct message typing related events are enabled. See also :attr:`dm_typing` for DMs or :attr:`typing` for both. This corresponds to the following events: - :func:`on_typing` (only for guilds) This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 11 @flag_value def dm_typing(self): """:class:`bool`: Whether guild and direct message typing related events are enabled. See also :attr:`guild_typing` for guilds or :attr:`typing` for both. This corresponds to the following events: - :func:`on_typing` (only for DMs) This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 14 @fill_with_flags() class MemberCacheFlags(BaseFlags): """Controls the library's cache policy when it comes to members. This allows for finer grained control over what members are cached. Note that the bot's own member is always cached. This class is passed to the ``member_cache_flags`` parameter in :class:`Client`. Due to a quirk in how Discord works, in order to ensure proper cleanup of cache resources it is recommended to have :attr:`Intents.members` enabled. Otherwise the library cannot know when a member leaves a guild and is thus unable to cleanup after itself. To construct an object you can pass keyword arguments denoting the flags to enable or disable. The default value is all flags enabled. .. versionadded:: 1.5 .. container:: operations .. describe:: x == y Checks if two flags are equal. .. describe:: x != y Checks if two flags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Attributes ----------- value: :class:`int` The raw value. You should query flags via the properties rather than using this raw value. """ __slots__ = () def __init__(self, **kwargs: bool): bits = max(self.VALID_FLAGS.values()).bit_length() self.value = (1 << bits) - 1 for key, value in kwargs.items(): if key not in self.VALID_FLAGS: raise TypeError(f'{key!r} is not a valid flag name.') setattr(self, key, value) @classmethod def all(cls: Type[MemberCacheFlags]) -> MemberCacheFlags: """A factory method that creates a :class:`MemberCacheFlags` with everything enabled.""" bits = max(cls.VALID_FLAGS.values()).bit_length() value = (1 << bits) - 1 self = cls.__new__(cls) self.value = value return self @classmethod def none(cls: Type[MemberCacheFlags]) -> MemberCacheFlags: """A factory method that creates a :class:`MemberCacheFlags` with everything disabled.""" self = cls.__new__(cls) self.value = self.DEFAULT_VALUE return self @property def _empty(self): return self.value == self.DEFAULT_VALUE @flag_value def voice(self): """:class:`bool`: Whether to cache members that are in voice. This requires :attr:`Intents.voice_states`. Members that leave voice are no longer cached. """ return 1 @flag_value def joined(self): """:class:`bool`: Whether to cache members that joined the guild or are chunked as part of the initial log in flow. This requires :attr:`Intents.members`. Members that leave the guild are no longer cached. """ return 2 @classmethod def from_intents(cls: Type[MemberCacheFlags], intents: Intents) -> MemberCacheFlags: """A factory method that creates a :class:`MemberCacheFlags` based on the currently selected :class:`Intents`. Parameters ------------ intents: :class:`Intents` The intents to select from. Returns --------- :class:`MemberCacheFlags` The resulting member cache flags. """ self = cls.none() if intents.members: self.joined = True if intents.voice_states: self.voice = True return self def _verify_intents(self, intents: Intents): if self.voice and not intents.voice_states: raise ValueError('MemberCacheFlags.voice requires Intents.voice_states') if self.joined and not intents.members: raise ValueError('MemberCacheFlags.joined requires Intents.members') @property def _voice_only(self): return self.value == 1 @fill_with_flags() class ApplicationFlags(BaseFlags): r"""Wraps up the Discord Application flags. .. container:: operations .. describe:: x == y Checks if two ApplicationFlags are equal. .. describe:: x != y Checks if two ApplicationFlags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown. .. versionadded:: 2.0 Attributes ----------- value: :class:`int` The raw value. You should query flags via the properties rather than using this raw value. """ @flag_value def gateway_presence(self): """:class:`bool`: Returns ``True`` if the application is verified and is allowed to receive presence information over the gateway. """ return 1 << 12 @flag_value def gateway_presence_limited(self): """:class:`bool`: Returns ``True`` if the application is allowed to receive limited presence information over the gateway. """ return 1 << 13 @flag_value def gateway_guild_members(self): """:class:`bool`: Returns ``True`` if the application is verified and is allowed to receive guild members information over the gateway. """ return 1 << 14 @flag_value def gateway_guild_members_limited(self): """:class:`bool`: Returns ``True`` if the application is allowed to receive limited guild members information over the gateway. """ return 1 << 15 @flag_value def verification_pending_guild_limit(self): """:class:`bool`: Returns ``True`` if the application is currently pending verification and has hit the guild limit. """ return 1 << 16 @flag_value def embedded(self): """:class:`bool`: Returns ``True`` if the application is embedded within the Discord client.""" return 1 << 17
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/flags.py
flags.py
from __future__ import annotations from typing import Any, Dict, Optional, TYPE_CHECKING, Type, TypeVar, Union import re from .asset import Asset, AssetMixin from .errors import InvalidArgument from . import utils __all__ = ( 'PartialEmoji', ) if TYPE_CHECKING: from .state import ConnectionState from datetime import datetime from .types.message import PartialEmoji as PartialEmojiPayload class _EmojiTag: __slots__ = () id: int def _to_partial(self) -> PartialEmoji: raise NotImplementedError PE = TypeVar('PE', bound='PartialEmoji') class PartialEmoji(_EmojiTag, AssetMixin): """Represents a "partial" emoji. This model will be given in two scenarios: - "Raw" data events such as :func:`on_raw_reaction_add` - Custom emoji that the bot cannot see from e.g. :attr:`Message.reactions` .. container:: operations .. describe:: x == y Checks if two emoji are the same. .. describe:: x != y Checks if two emoji are not the same. .. describe:: hash(x) Return the emoji's hash. .. describe:: str(x) Returns the emoji rendered for discord. Attributes ----------- name: Optional[:class:`str`] The custom emoji name, if applicable, or the unicode codepoint of the non-custom emoji. This can be ``None`` if the emoji got deleted (e.g. removing a reaction with a deleted emoji). animated: :class:`bool` Whether the emoji is animated or not. id: Optional[:class:`int`] The ID of the custom emoji, if applicable. """ __slots__ = ('animated', 'name', 'id', '_state') _CUSTOM_EMOJI_RE = re.compile(r'<?(?P<animated>a)?:?(?P<name>[A-Za-z0-9\_]+):(?P<id>[0-9]{13,20})>?') if TYPE_CHECKING: id: Optional[int] def __init__(self, *, name: str, animated: bool = False, id: Optional[int] = None): self.animated = animated self.name = name self.id = id self._state: Optional[ConnectionState] = None @classmethod def from_dict(cls: Type[PE], data: Union[PartialEmojiPayload, Dict[str, Any]]) -> PE: return cls( animated=data.get('animated', False), id=utils._get_as_snowflake(data, 'id'), name=data.get('name') or '', ) @classmethod def from_str(cls: Type[PE], value: str) -> PE: """Converts a Discord string representation of an emoji to a :class:`PartialEmoji`. The formats accepted are: - ``a:name:id`` - ``<a:name:id>`` - ``name:id`` - ``<:name:id>`` If the format does not match then it is assumed to be a unicode emoji. .. versionadded:: 2.0 Parameters ------------ value: :class:`str` The string representation of an emoji. Returns -------- :class:`PartialEmoji` The partial emoji from this string. """ match = cls._CUSTOM_EMOJI_RE.match(value) if match is not None: groups = match.groupdict() animated = bool(groups['animated']) emoji_id = int(groups['id']) name = groups['name'] return cls(name=name, animated=animated, id=emoji_id) return cls(name=value, id=None, animated=False) def to_dict(self) -> Dict[str, Any]: o: Dict[str, Any] = {'name': self.name} if self.id: o['id'] = self.id if self.animated: o['animated'] = self.animated return o def _to_partial(self) -> PartialEmoji: return self @classmethod def with_state( cls: Type[PE], state: ConnectionState, *, name: str, animated: bool = False, id: Optional[int] = None ) -> PE: self = cls(name=name, animated=animated, id=id) self._state = state return self def __str__(self) -> str: if self.id is None: return self.name if self.animated: return f'<a:{self.name}:{self.id}>' return f'<:{self.name}:{self.id}>' def __repr__(self): return f'<{self.__class__.__name__} animated={self.animated} name={self.name!r} id={self.id}>' def __eq__(self, other: Any) -> bool: if self.is_unicode_emoji(): return isinstance(other, PartialEmoji) and self.name == other.name if isinstance(other, _EmojiTag): return self.id == other.id return False def __ne__(self, other: Any) -> bool: return not self.__eq__(other) def __hash__(self) -> int: return hash((self.id, self.name)) def is_custom_emoji(self) -> bool: """:class:`bool`: Checks if this is a custom non-Unicode emoji.""" return self.id is not None def is_unicode_emoji(self) -> bool: """:class:`bool`: Checks if this is a Unicode emoji.""" return self.id is None def _as_reaction(self) -> str: if self.id is None: return self.name return f'{self.name}:{self.id}' @property def created_at(self) -> Optional[datetime]: """Optional[:class:`datetime.datetime`]: Returns the emoji's creation time in UTC, or None if Unicode emoji. .. versionadded:: 1.6 """ if self.id is None: return None return utils.snowflake_time(self.id) @property def url(self) -> str: """:class:`str`: Returns the URL of the emoji, if it is custom. If this isn't a custom emoji then an empty string is returned """ if self.is_unicode_emoji(): return '' fmt = 'gif' if self.animated else 'png' return f'{Asset.BASE}/emojis/{self.id}.{fmt}' async def read(self) -> bytes: if self.is_unicode_emoji(): raise InvalidArgument('PartialEmoji is not a custom emoji') return await super().read()
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/partial_emoji.py
partial_emoji.py
from __future__ import annotations from . import utils from .user import BaseUser from .asset import Asset from .enums import TeamMembershipState, try_enum from typing import TYPE_CHECKING, Optional, List if TYPE_CHECKING: from .state import ConnectionState from .types.team import ( Team as TeamPayload, TeamMember as TeamMemberPayload, ) __all__ = ( 'Team', 'TeamMember', ) class Team: """Represents an application team for a bot provided by Discord. Attributes ------------- id: :class:`int` The team ID. name: :class:`str` The team name owner_id: :class:`int` The team's owner ID. members: List[:class:`TeamMember`] A list of the members in the team .. versionadded:: 1.3 """ __slots__ = ('_state', 'id', 'name', '_icon', 'owner_id', 'members') def __init__(self, state: ConnectionState, data: TeamPayload): self._state: ConnectionState = state self.id: int = int(data['id']) self.name: str = data['name'] self._icon: Optional[str] = data['icon'] self.owner_id: Optional[int] = utils._get_as_snowflake(data, 'owner_user_id') self.members: List[TeamMember] = [TeamMember(self, self._state, member) for member in data['members']] def __repr__(self) -> str: return f'<{self.__class__.__name__} id={self.id} name={self.name}>' @property def icon(self) -> Optional[Asset]: """Optional[:class:`.Asset`]: Retrieves the team's icon asset, if any.""" if self._icon is None: return None return Asset._from_icon(self._state, self.id, self._icon, path='team') @property def owner(self) -> Optional[TeamMember]: """Optional[:class:`TeamMember`]: The team's owner.""" return utils.get(self.members, id=self.owner_id) class TeamMember(BaseUser): """Represents a team member in a team. .. container:: operations .. describe:: x == y Checks if two team members are equal. .. describe:: x != y Checks if two team members are not equal. .. describe:: hash(x) Return the team member's hash. .. describe:: str(x) Returns the team member's name with discriminator. .. versionadded:: 1.3 Attributes ------------- name: :class:`str` The team member's username. id: :class:`int` The team member's unique ID. discriminator: :class:`str` The team member's discriminator. This is given when the username has conflicts. avatar: Optional[:class:`str`] The avatar hash the team member has. Could be None. bot: :class:`bool` Specifies if the user is a bot account. team: :class:`Team` The team that the member is from. membership_state: :class:`TeamMembershipState` The membership state of the member (e.g. invited or accepted) """ __slots__ = ('team', 'membership_state', 'permissions') def __init__(self, team: Team, state: ConnectionState, data: TeamMemberPayload): self.team: Team = team self.membership_state: TeamMembershipState = try_enum(TeamMembershipState, data['membership_state']) self.permissions: List[str] = data['permissions'] super().__init__(state=state, data=data['user']) def __repr__(self) -> str: return ( f'<{self.__class__.__name__} id={self.id} name={self.name!r} ' f'discriminator={self.discriminator!r} membership_state={self.membership_state!r}>' )
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/team.py
team.py
from __future__ import annotations import datetime import inspect import itertools import sys from operator import attrgetter from typing import Any, Dict, List, Literal, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Union, overload import discord.abc from . import utils from .asset import Asset from .utils import MISSING from .user import BaseUser, User, _UserTag from .activity import create_activity, ActivityTypes from .permissions import Permissions from .enums import Status, try_enum from .colour import Colour from .object import Object __all__ = ( 'VoiceState', 'Member', ) if TYPE_CHECKING: from .asset import Asset from .channel import DMChannel, VoiceChannel, StageChannel from .flags import PublicUserFlags from .guild import Guild from .types.activity import PartialPresenceUpdate from .types.member import ( MemberWithUser as MemberWithUserPayload, Member as MemberPayload, UserWithMember as UserWithMemberPayload, ) from .types.user import User as UserPayload from .abc import Snowflake from .state import ConnectionState from .message import Message from .role import Role from .types.voice import VoiceState as VoiceStatePayload VocalGuildChannel = Union[VoiceChannel, StageChannel] class VoiceState: """Represents a Discord user's voice state. Attributes ------------ deaf: :class:`bool` Indicates if the user is currently deafened by the guild. mute: :class:`bool` Indicates if the user is currently muted by the guild. self_mute: :class:`bool` Indicates if the user is currently muted by their own accord. self_deaf: :class:`bool` Indicates if the user is currently deafened by their own accord. self_stream: :class:`bool` Indicates if the user is currently streaming via 'Go Live' feature. .. versionadded:: 1.3 self_video: :class:`bool` Indicates if the user is currently broadcasting video. suppress: :class:`bool` Indicates if the user is suppressed from speaking. Only applies to stage channels. .. versionadded:: 1.7 requested_to_speak_at: Optional[:class:`datetime.datetime`] An aware datetime object that specifies the date and time in UTC that the member requested to speak. It will be ``None`` if they are not requesting to speak anymore or have been accepted to speak. Only applicable to stage channels. .. versionadded:: 1.7 afk: :class:`bool` Indicates if the user is currently in the AFK channel in the guild. channel: Optional[Union[:class:`VoiceChannel`, :class:`StageChannel`]] The voice channel that the user is currently connected to. ``None`` if the user is not currently in a voice channel. """ __slots__ = ( 'session_id', 'deaf', 'mute', 'self_mute', 'self_stream', 'self_video', 'self_deaf', 'afk', 'channel', 'requested_to_speak_at', 'suppress', ) def __init__(self, *, data: VoiceStatePayload, channel: Optional[VocalGuildChannel] = None): self.session_id: str = data.get('session_id') self._update(data, channel) def _update(self, data: VoiceStatePayload, channel: Optional[VocalGuildChannel]): self.self_mute: bool = data.get('self_mute', False) self.self_deaf: bool = data.get('self_deaf', False) self.self_stream: bool = data.get('self_stream', False) self.self_video: bool = data.get('self_video', False) self.afk: bool = data.get('suppress', False) self.mute: bool = data.get('mute', False) self.deaf: bool = data.get('deaf', False) self.suppress: bool = data.get('suppress', False) self.requested_to_speak_at: Optional[datetime.datetime] = utils.parse_time(data.get('request_to_speak_timestamp')) self.channel: Optional[VocalGuildChannel] = channel def __repr__(self) -> str: attrs = [ ('self_mute', self.self_mute), ('self_deaf', self.self_deaf), ('self_stream', self.self_stream), ('suppress', self.suppress), ('requested_to_speak_at', self.requested_to_speak_at), ('channel', self.channel), ] inner = ' '.join('%s=%r' % t for t in attrs) return f'<{self.__class__.__name__} {inner}>' 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): # We want sphinx to properly show coroutine functions as coroutines if inspect.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) func = utils.copy_doc(value)(func) setattr(cls, attr, func) return cls M = TypeVar('M', bound='Member') @flatten_user class Member(discord.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 :issue:`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', ) if TYPE_CHECKING: name: str id: int 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): 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, ...] = tuple() self.nick: Optional[str] = data.get('nick', None) self.pending: bool = data.get('pending', False) self._avatar: Optional[str] = data.get('avatar') def __str__(self) -> str: return str(self._user) def __repr__(self) -> str: return ( f'<Member id={self._user.id} name={self._user.name!r} discriminator={self._user.discriminator!r}' 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) @classmethod def _from_message(cls: Type[M], *, message: Message, data: MemberPayload) -> M: 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) @classmethod def _try_upgrade(cls: Type[M], *, data: UserWithMemberPayload, guild: Guild, state: ConnectionState) -> Union[User, M]: # 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 @classmethod def _copy(cls: Type[M], member: M) -> M: self: M = 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 # Reference will not be copied unless necessary by PRESENCE_UPDATE # See below self._user = member._user return self async def _get_channel(self): ch = await self.create_dm() return ch def _update(self, data: MemberPayload) -> None: # the nickname change is optional, # if it isn't in the payload then it didn't change try: self.nick = data['nick'] except KeyError: pass try: self.pending = data['pending'] except KeyError: pass self.premium_since = utils.parse_time(data.get('premium_since')) self._roles = utils.SnowflakeList(map(int, data['roles'])) self._avatar = data.get('avatar') def _presence_update(self, data: PartialPresenceUpdate, user: UserPayload) -> Optional[Tuple[User, User]]: self.activities = tuple(map(create_activity, 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 @property def status(self) -> Status: """:class:`Status`: 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]) @property def raw_status(self) -> str: """:class:`str`: The member's overall status as a string value. .. versionadded:: 1.5 """ return self._client_status[None] @status.setter def status(self, value: Status) -> None: # internal use only self._client_status[None] = str(value) @property 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')) @property 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')) @property 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 @property 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() @property 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 @property 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 @property def mention(self) -> str: """:class:`str`: Returns a string that allows you to mention the member.""" if self.nick: return f'<@!{self._user.id}>' return f'<@{self._user.id}>' @property 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 @property 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 @property 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) @property 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 :issue:`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] 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) @property 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) @property 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 @property def voice(self) -> Optional[VoiceState]: """Optional[:class:`VoiceState`]: Returns the member's current voice state.""" return self.guild._voice_state_for(self._user.id) async def ban( self, *, delete_message_days: Literal[0, 1, 2, 3, 4, 5, 6, 7] = 1, reason: Optional[str] = None, ) -> None: """|coro| Bans this member. Equivalent to :meth:`Guild.ban`. """ await self.guild.ban(self, reason=reason, 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 edit( self, *, nick: Optional[str] = MISSING, mute: bool = MISSING, deafen: bool = MISSING, suppress: bool = MISSING, roles: List[discord.abc.Snowflake] = MISSING, voice_channel: Optional[VocalGuildChannel] = MISSING, reason: Optional[str] = None, ) -> 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` | +---------------+--------------------------------------+ 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. 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: voice_state_payload = { 'channel_id': self.voice.channel.id, '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'] = datetime.datetime.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 payload: data = await http.edit_member(guild_id, self.id, reason=reason, **payload) return Member(data=data, guild=self.guild, state=self._state) 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, 'request_to_speak_timestamp': datetime.datetime.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: 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 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 = 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 = [Object(id=r.id) for r in self.roles[1:]] # remove @everyone for role in roles: try: new_roles.remove(Object(id=role.id)) except ValueError: pass 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
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/member.py
member.py
from __future__ import annotations from typing import Callable, Any, ClassVar, Dict, Iterator, Set, TYPE_CHECKING, Tuple, Type, TypeVar, Optional from .flags import BaseFlags, flag_value, fill_with_flags, alias_flag_value __all__ = ( 'Permissions', 'PermissionOverwrite', ) # A permission alias works like a regular flag but is marked # So the PermissionOverwrite knows to work with it 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 P = TypeVar('P', bound='Permissions') @fill_with_flags() 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): 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 else: 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 else: 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 @classmethod def none(cls: Type[P]) -> P: """A factory method that creates a :class:`Permissions` with all permissions set to ``False``.""" return cls(0) @classmethod def all(cls: Type[P]) -> P: """A factory method that creates a :class:`Permissions` with all permissions set to ``True``. """ return cls(0b111111111111111111111111111111111111111) @classmethod def all_channel(cls: Type[P]) -> P: """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) @classmethod def general(cls: Type[P]) -> P: """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) @classmethod def membership(cls: Type[P]) -> P: """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) @classmethod def text(cls: Type[P]) -> P: """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) @classmethod def voice(cls: Type[P]) -> P: """A factory method that creates a :class:`Permissions` with all "Voice" permissions from the official Discord UI set to ``True``.""" return cls(0b00000011111100000000001100000000) @classmethod def stage(cls: Type[P]) -> P: """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) @classmethod def stage_moderator(cls: Type[P]) -> P: """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) @classmethod def advanced(cls: Type[P]) -> P: """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 @flag_value def create_instant_invite(self) -> int: """:class:`bool`: Returns ``True`` if the user can create instant invites.""" return 1 << 0 @flag_value def kick_members(self) -> int: """:class:`bool`: Returns ``True`` if the user can kick users from the guild.""" return 1 << 1 @flag_value def ban_members(self) -> int: """:class:`bool`: Returns ``True`` if a user can ban users from the guild.""" return 1 << 2 @flag_value 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 @flag_value 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 @flag_value def manage_guild(self) -> int: """:class:`bool`: Returns ``True`` if a user can edit guild properties.""" return 1 << 5 @flag_value def add_reactions(self) -> int: """:class:`bool`: Returns ``True`` if a user can add reactions to messages.""" return 1 << 6 @flag_value def view_audit_log(self) -> int: """:class:`bool`: Returns ``True`` if a user can view the guild's audit log.""" return 1 << 7 @flag_value def priority_speaker(self) -> int: """:class:`bool`: Returns ``True`` if a user can be more easily heard while talking.""" return 1 << 8 @flag_value def stream(self) -> int: """:class:`bool`: Returns ``True`` if a user can stream in a voice channel.""" return 1 << 9 @flag_value def read_messages(self) -> int: """:class:`bool`: Returns ``True`` if a user can read messages from all or specific text channels.""" return 1 << 10 @make_permission_alias('read_messages') def view_channel(self) -> int: """:class:`bool`: An alias for :attr:`read_messages`. .. versionadded:: 1.3 """ return 1 << 10 @flag_value def send_messages(self) -> int: """:class:`bool`: Returns ``True`` if a user can send messages from all or specific text channels.""" return 1 << 11 @flag_value 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 @flag_value 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 @flag_value def embed_links(self) -> int: """:class:`bool`: Returns ``True`` if a user's messages will automatically be embedded by Discord.""" return 1 << 14 @flag_value def attach_files(self) -> int: """:class:`bool`: Returns ``True`` if a user can send files in their messages.""" return 1 << 15 @flag_value def read_message_history(self) -> int: """:class:`bool`: Returns ``True`` if a user can read a text channel's previous messages.""" return 1 << 16 @flag_value 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 @flag_value def external_emojis(self) -> int: """:class:`bool`: Returns ``True`` if a user can use emojis from other guilds.""" return 1 << 18 @make_permission_alias('external_emojis') def use_external_emojis(self) -> int: """:class:`bool`: An alias for :attr:`external_emojis`. .. versionadded:: 1.3 """ return 1 << 18 @flag_value 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 @flag_value def connect(self) -> int: """:class:`bool`: Returns ``True`` if a user can connect to a voice channel.""" return 1 << 20 @flag_value def speak(self) -> int: """:class:`bool`: Returns ``True`` if a user can speak in a voice channel.""" return 1 << 21 @flag_value def mute_members(self) -> int: """:class:`bool`: Returns ``True`` if a user can mute other users.""" return 1 << 22 @flag_value def deafen_members(self) -> int: """:class:`bool`: Returns ``True`` if a user can deafen other users.""" return 1 << 23 @flag_value def move_members(self) -> int: """:class:`bool`: Returns ``True`` if a user can move users between other voice channels.""" return 1 << 24 @flag_value def use_voice_activation(self) -> int: """:class:`bool`: Returns ``True`` if a user can use voice activation in voice channels.""" return 1 << 25 @flag_value def change_nickname(self) -> int: """:class:`bool`: Returns ``True`` if a user can change their nickname in the guild.""" return 1 << 26 @flag_value def manage_nicknames(self) -> int: """:class:`bool`: Returns ``True`` if a user can change other user's nickname in the guild.""" return 1 << 27 @flag_value 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 @make_permission_alias('manage_roles') def manage_permissions(self) -> int: """:class:`bool`: An alias for :attr:`manage_roles`. .. versionadded:: 1.3 """ return 1 << 28 @flag_value def manage_webhooks(self) -> int: """:class:`bool`: Returns ``True`` if a user can create, edit, or delete webhooks.""" return 1 << 29 @flag_value def manage_emojis(self) -> int: """:class:`bool`: Returns ``True`` if a user can create, edit, or delete emojis.""" return 1 << 30 @make_permission_alias('manage_emojis') def manage_emojis_and_stickers(self) -> int: """:class:`bool`: An alias for :attr:`manage_emojis`. .. versionadded:: 2.0 """ return 1 << 30 @flag_value def use_slash_commands(self) -> int: """:class:`bool`: Returns ``True`` if a user can use slash commands. .. versionadded:: 1.7 """ return 1 << 31 @flag_value 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 @flag_value def manage_events(self) -> int: """:class:`bool`: Returns ``True`` if a user can manage guild events. .. versionadded:: 2.0 """ return 1 << 33 @flag_value def manage_threads(self) -> int: """:class:`bool`: Returns ``True`` if a user can manage threads. .. versionadded:: 2.0 """ return 1 << 34 @flag_value def create_public_threads(self) -> int: """:class:`bool`: Returns ``True`` if a user can create public threads. .. versionadded:: 2.0 """ return 1 << 35 @flag_value def create_private_threads(self) -> int: """:class:`bool`: Returns ``True`` if a user can create private threads. .. versionadded:: 2.0 """ return 1 << 36 @flag_value def external_stickers(self) -> int: """:class:`bool`: Returns ``True`` if a user can use stickers from other guilds. .. versionadded:: 2.0 """ return 1 << 37 @make_permission_alias('external_stickers') def use_external_stickers(self) -> int: """:class:`bool`: An alias for :attr:`external_stickers`. .. versionadded:: 2.0 """ return 1 << 37 @flag_value def send_messages_in_threads(self) -> int: """:class:`bool`: Returns ``True`` if a user can send messages in threads. .. versionadded:: 2.0 """ return 1 << 38 PO = TypeVar('PO', bound='PermissionOverwrite') 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): self._set(x, value) prop = property(getter, setter) setattr(cls, name, prop) cls.PURE_FLAGS = cls.VALID_NAMES - aliases return cls @_augment_from_permissions 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] def __init__(self, **kwargs: Optional[bool]): 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 @classmethod def from_pair(cls: Type[PO], allow: Permissions, deny: Permissions) -> PO: """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)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/permissions.py
permissions.py
from __future__ import annotations from typing import List, TYPE_CHECKING, Optional from . import utils from .asset import Asset if TYPE_CHECKING: from .guild import Guild from .types.appinfo import ( AppInfo as AppInfoPayload, PartialAppInfo as PartialAppInfoPayload, Team as TeamPayload, ) from .user import User from .state import ConnectionState __all__ = ( 'AppInfo', 'PartialAppInfo', ) class AppInfo: """Represents the application info for the bot provided by Discord. Attributes ------------- id: :class:`int` The application ID. name: :class:`str` The application name. owner: :class:`User` The application owner. team: Optional[:class:`Team`] The application's team. .. versionadded:: 1.3 description: :class:`str` The application description. bot_public: :class:`bool` Whether the bot can be invited by anyone or if it is locked to the application owner. bot_require_code_grant: :class:`bool` Whether the bot requires the completion of the full oauth2 code grant flow to join. rpc_origins: Optional[List[:class:`str`]] A list of RPC origin URLs, if RPC is enabled. summary: :class:`str` If this application is a game sold on Discord, this field will be the summary field for the store page of its primary SKU. .. versionadded:: 1.3 verify_key: :class:`str` The hex encoded key for verification in interactions and the GameSDK's `GetTicket <https://discord.com/developers/docs/game-sdk/applications#getticket>`_. .. versionadded:: 1.3 guild_id: Optional[:class:`int`] If this application is a game sold on Discord, this field will be the guild to which it has been linked to. .. versionadded:: 1.3 primary_sku_id: Optional[:class:`int`] If this application is a game sold on Discord, this field will be the id of the "Game SKU" that is created, if it exists. .. versionadded:: 1.3 slug: Optional[:class:`str`] If this application is a game sold on Discord, this field will be the URL slug that links to the store page. .. versionadded:: 1.3 terms_of_service_url: Optional[:class:`str`] The application's terms of service URL, if set. .. versionadded:: 2.0 privacy_policy_url: Optional[:class:`str`] The application's privacy policy URL, if set. .. versionadded:: 2.0 """ __slots__ = ( '_state', 'description', 'id', 'name', 'rpc_origins', 'bot_public', 'bot_require_code_grant', 'owner', '_icon', 'summary', 'verify_key', 'team', 'guild_id', 'primary_sku_id', 'slug', '_cover_image', 'terms_of_service_url', 'privacy_policy_url', ) def __init__(self, state: ConnectionState, data: AppInfoPayload): from .team import Team self._state: ConnectionState = state self.id: int = int(data['id']) self.name: str = data['name'] self.description: str = data['description'] self._icon: Optional[str] = data['icon'] self.rpc_origins: List[str] = data['rpc_origins'] self.bot_public: bool = data['bot_public'] self.bot_require_code_grant: bool = data['bot_require_code_grant'] self.owner: User = state.create_user(data['owner']) team: Optional[TeamPayload] = data.get('team') self.team: Optional[Team] = Team(state, team) if team else None self.summary: str = data['summary'] self.verify_key: str = data['verify_key'] self.guild_id: Optional[int] = utils._get_as_snowflake(data, 'guild_id') self.primary_sku_id: Optional[int] = utils._get_as_snowflake(data, 'primary_sku_id') self.slug: Optional[str] = data.get('slug') self._cover_image: Optional[str] = data.get('cover_image') self.terms_of_service_url: Optional[str] = data.get('terms_of_service_url') self.privacy_policy_url: Optional[str] = data.get('privacy_policy_url') def __repr__(self) -> str: return ( f'<{self.__class__.__name__} id={self.id} name={self.name!r} ' f'description={self.description!r} public={self.bot_public} ' f'owner={self.owner!r}>' ) @property def icon(self) -> Optional[Asset]: """Optional[:class:`.Asset`]: Retrieves the application's icon asset, if any.""" if self._icon is None: return None return Asset._from_icon(self._state, self.id, self._icon, path='app') @property def cover_image(self) -> Optional[Asset]: """Optional[:class:`.Asset`]: Retrieves the cover image on a store embed, if any. This is only available if the application is a game sold on Discord. """ if self._cover_image is None: return None return Asset._from_cover_image(self._state, self.id, self._cover_image) @property def guild(self) -> Optional[Guild]: """Optional[:class:`Guild`]: If this application is a game sold on Discord, this field will be the guild to which it has been linked .. versionadded:: 1.3 """ return self._state._get_guild(self.guild_id) class PartialAppInfo: """Represents a partial AppInfo given by :func:`~discord.abc.GuildChannel.create_invite` .. versionadded:: 2.0 Attributes ------------- id: :class:`int` The application ID. name: :class:`str` The application name. description: :class:`str` The application description. rpc_origins: Optional[List[:class:`str`]] A list of RPC origin URLs, if RPC is enabled. summary: :class:`str` If this application is a game sold on Discord, this field will be the summary field for the store page of its primary SKU. verify_key: :class:`str` The hex encoded key for verification in interactions and the GameSDK's `GetTicket <https://discord.com/developers/docs/game-sdk/applications#getticket>`_. terms_of_service_url: Optional[:class:`str`] The application's terms of service URL, if set. privacy_policy_url: Optional[:class:`str`] The application's privacy policy URL, if set. """ __slots__ = ('_state', 'id', 'name', 'description', 'rpc_origins', 'summary', 'verify_key', 'terms_of_service_url', 'privacy_policy_url', '_icon') def __init__(self, *, state: ConnectionState, data: PartialAppInfoPayload): self._state: ConnectionState = state self.id: int = int(data['id']) self.name: str = data['name'] self._icon: Optional[str] = data.get('icon') self.description: str = data['description'] self.rpc_origins: Optional[List[str]] = data.get('rpc_origins') self.summary: str = data['summary'] self.verify_key: str = data['verify_key'] self.terms_of_service_url: Optional[str] = data.get('terms_of_service_url') self.privacy_policy_url: Optional[str] = data.get('privacy_policy_url') def __repr__(self) -> str: return f'<{self.__class__.__name__} id={self.id} name={self.name!r} description={self.description!r}>' @property def icon(self) -> Optional[Asset]: """Optional[:class:`.Asset`]: Retrieves the application's icon asset, if any.""" if self._icon is None: return None return Asset._from_icon(self._state, self.id, self._icon, path='app')
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/appinfo.py
appinfo.py
from __future__ import annotations from typing import Any, Dict, List, Optional, TYPE_CHECKING, Tuple, Union import asyncio from . import utils from .enums import try_enum, InteractionType, InteractionResponseType from .errors import InteractionResponded, HTTPException, ClientException from .channel import PartialMessageable, ChannelType from .user import User from .member import Member from .message import Message, Attachment from .object import Object from .permissions import Permissions from .webhook.async_ import async_context, Webhook, handle_message_parameters __all__ = ( 'Interaction', 'InteractionMessage', 'InteractionResponse', ) if TYPE_CHECKING: from .types.interactions import ( Interaction as InteractionPayload, InteractionData, ) from .guild import Guild from .state import ConnectionState from .file import File from .mentions import AllowedMentions from aiohttp import ClientSession from .embeds import Embed from .ui.view import View from .channel import VoiceChannel, StageChannel, TextChannel, CategoryChannel, StoreChannel, PartialMessageable from .threads import Thread InteractionChannel = Union[ VoiceChannel, StageChannel, TextChannel, CategoryChannel, StoreChannel, Thread, PartialMessageable ] MISSING: Any = utils.MISSING class Interaction: """Represents a Discord interaction. An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components. .. versionadded:: 2.0 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. 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. """ __slots__: Tuple[str, ...] = ( 'id', 'type', 'guild_id', 'channel_id', 'data', 'application_id', 'message', 'user', 'token', 'version', '_permissions', '_state', '_session', '_original_message', '_cs_response', '_cs_followup', '_cs_channel', ) def __init__(self, *, data: InteractionPayload, state: ConnectionState): self._state: ConnectionState = state self._session: ClientSession = state.http._HTTPClient__session self._original_message: Optional[InteractionMessage] = None self._from_data(data) def _from_data(self, data: InteractionPayload): 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.message: Optional[Message] try: self.message = Message(state=self._state, channel=self.channel, data=data['message']) # type: ignore except KeyError: self.message = None self.user: Optional[Union[User, Member]] = None 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'] # type: ignore except KeyError: pass else: self.user = Member(state=self._state, guild=guild, data=member) # type: ignore self._permissions = int(member.get('permissions', 0)) else: try: self.user = User(state=self._state, data=data['user']) except KeyError: pass @property 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) @utils.cached_slot_property('_cs_channel') 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 @property 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) @utils.cached_slot_property('_cs_response') 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) @utils.cached_slot_property('_cs_followup') 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, 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. allowed_mentions: :class:`AllowedMentions` Controls the mentions being processed in this message. See :meth:`.abc.Messageable.send` for more information. view: Optional[:class:`~discord.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. TypeError 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, 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(): self._state.store_view(view, message.id) return message async def delete_original_message(self) -> 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. Raises ------- HTTPException Deleting the message failed. Forbidden Deleted a message that is not yours. """ adapter = async_context.get() await adapter.delete_original_interaction_response( self.application_id, self.token, session=self._session, ) class InteractionResponse: """Represents a Discord interaction response. This type can be accessed through :attr:`Interaction.response`. .. versionadded:: 2.0 """ __slots__: Tuple[str, ...] = ( '_responded', '_parent', ) def __init__(self, parent: Interaction): self._parent: Interaction = parent self._responded: bool = False def is_done(self) -> bool: """:class:`bool`: Indicates whether an interaction response has been done before. An interaction can only be responded to once. """ return self._responded async def defer(self, *, ephemeral: bool = False) -> None: """|coro| Defers the interaction response. This is typically used when the interaction is acknowledged and a secondary action will be done later. Parameters ----------- ephemeral: :class:`bool` Indicates whether the deferred message will eventually be ephemeral. This only applies for interactions of type :attr:`InteractionType.application_command`. Raises ------- HTTPException Deferring the interaction failed. InteractionResponded This interaction has already been responded to before. """ if self._responded: raise InteractionResponded(self._parent) defer_type: int = 0 data: Optional[Dict[str, Any]] = None parent = self._parent if parent.type is InteractionType.component: defer_type = InteractionResponseType.deferred_message_update.value elif parent.type is InteractionType.application_command: defer_type = InteractionResponseType.deferred_channel_message.value if ephemeral: data = {'flags': 64} if defer_type: adapter = async_context.get() await adapter.create_interaction_response( parent.id, parent.token, session=parent._session, type=defer_type, data=data ) self._responded = True async def pong(self) -> None: """|coro| Pongs the ping interaction. This should rarely be used. Raises ------- HTTPException Ponging the interaction failed. InteractionResponded This interaction has already been responded to before. """ if self._responded: raise InteractionResponded(self._parent) parent = self._parent if parent.type is InteractionType.ping: adapter = async_context.get() await adapter.create_interaction_response( parent.id, parent.token, session=parent._session, type=InteractionResponseType.pong.value ) self._responded = True async def send_message( self, content: Optional[Any] = None, *, embed: Embed = MISSING, embeds: List[Embed] = MISSING, view: View = MISSING, tts: bool = False, ephemeral: bool = False, ) -> None: """|coro| Responds to this interaction by sending a message. Parameters ----------- content: Optional[:class:`str`] The content of the message to send. embeds: List[:class:`Embed`] A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the ``embed`` parameter. embed: :class:`Embed` The rich embed for the content to send. This cannot be mixed with ``embeds`` parameter. tts: :class:`bool` Indicates if the message should be sent using text-to-speech. view: :class:`discord.ui.View` The view to send with the message. ephemeral: :class:`bool` Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes. Raises ------- HTTPException Sending the message failed. TypeError You specified both ``embed`` and ``embeds``. ValueError The length of ``embeds`` was invalid. InteractionResponded This interaction has already been responded to before. """ if self._responded: raise InteractionResponded(self._parent) payload: Dict[str, Any] = { 'tts': tts, } if embed is not MISSING and embeds is not MISSING: raise TypeError('cannot mix embed and embeds keyword arguments') if embed is not MISSING: embeds = [embed] if embeds: if len(embeds) > 10: raise ValueError('embeds cannot exceed maximum of 10 elements') payload['embeds'] = [e.to_dict() for e in embeds] if content is not None: payload['content'] = str(content) if ephemeral: payload['flags'] = 64 if view is not MISSING: payload['components'] = view.to_components() parent = self._parent adapter = async_context.get() await adapter.create_interaction_response( parent.id, parent.token, session=parent._session, type=InteractionResponseType.channel_message.value, data=payload, ) if view is not MISSING: if ephemeral and view.timeout is None: view.timeout = 15 * 60.0 self._parent._state.store_view(view) self._responded = True async def edit_message( self, *, content: Optional[Any] = MISSING, embed: Optional[Embed] = MISSING, embeds: List[Embed] = MISSING, attachments: List[Attachment] = MISSING, view: Optional[View] = MISSING, ) -> None: """|coro| Responds to this interaction by editing the original message of a component interaction. Parameters ----------- content: Optional[:class:`str`] The new content to replace the message with. ``None`` removes the content. 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. attachments: List[:class:`Attachment`] A list of attachments to keep in the message. If ``[]`` is passed then all attachments are removed. view: Optional[:class:`~discord.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. TypeError You specified both ``embed`` and ``embeds``. InteractionResponded This interaction has already been responded to before. """ if self._responded: raise InteractionResponded(self._parent) parent = self._parent msg = parent.message state = parent._state message_id = msg.id if msg else None if parent.type is not InteractionType.component: return payload = {} if content is not MISSING: if content is None: payload['content'] = None else: payload['content'] = str(content) if embed is not MISSING and embeds is not MISSING: raise TypeError('cannot mix both embed and embeds keyword arguments') if embed is not MISSING: if embed is None: embeds = [] else: embeds = [embed] if embeds is not MISSING: payload['embeds'] = [e.to_dict() for e in embeds] if attachments is not MISSING: payload['attachments'] = [a.to_dict() for a in attachments] if view is not MISSING: state.prevent_view_updates_for(message_id) if view is None: payload['components'] = [] else: payload['components'] = view.to_components() adapter = async_context.get() await adapter.create_interaction_response( parent.id, parent.token, session=parent._session, type=InteractionResponseType.message_update.value, data=payload, ) if view and not view.is_finished(): state.store_view(view, message_id) self._responded = True class _InteractionMessageState: __slots__ = ('_parent', '_interaction') def __init__(self, interaction: Interaction, parent: ConnectionState): self._interaction: Interaction = interaction self._parent: ConnectionState = parent def _get_guild(self, guild_id): return self._parent._get_guild(guild_id) def store_user(self, data): return self._parent.store_user(data) def create_user(self, data): return self._parent.create_user(data) @property def http(self): return self._parent.http def __getattr__(self, attr): return getattr(self._parent, attr) class InteractionMessage(Message): """Represents the original interaction response message. This allows you to edit or delete the message associated with the interaction response. To retrieve this object see :meth:`Interaction.original_message`. This inherits from :class:`discord.Message` with changes to :meth:`edit` and :meth:`delete` to work. .. versionadded:: 2.0 """ __slots__ = () _state: _InteractionMessageState async def edit( self, content: Optional[str] = MISSING, embeds: List[Embed] = MISSING, embed: Optional[Embed] = MISSING, file: File = MISSING, files: List[File] = MISSING, view: Optional[View] = MISSING, allowed_mentions: Optional[AllowedMentions] = None, ) -> InteractionMessage: """|coro| Edits the message. 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. allowed_mentions: :class:`AllowedMentions` Controls the mentions being processed in this message. See :meth:`.abc.Messageable.send` for more information. view: Optional[:class:`~discord.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. TypeError You specified both ``embed`` and ``embeds`` or ``file`` and ``files`` ValueError The length of ``embeds`` was invalid. Returns --------- :class:`InteractionMessage` The newly edited message. """ return await self._state._interaction.edit_original_message( content=content, embeds=embeds, embed=embed, file=file, files=files, view=view, allowed_mentions=allowed_mentions, ) async def delete(self, *, delay: Optional[float] = None) -> None: """|coro| Deletes the message. 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 ------ 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 inner_call(delay: float = delay): await asyncio.sleep(delay) try: await self._state._interaction.delete_original_message() except HTTPException: pass asyncio.create_task(inner_call()) else: await self._state._interaction.delete_original_message()
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/interactions.py
interactions.py
from __future__ import annotations from typing import Literal, TYPE_CHECKING, List, Optional, Tuple, Type, Union import unicodedata from .mixins import Hashable from .asset import Asset, AssetMixin from .utils import cached_slot_property, find, snowflake_time, get, MISSING from .errors import InvalidData from .enums import StickerType, StickerFormatType, try_enum __all__ = ( 'StickerPack', 'StickerItem', 'Sticker', 'StandardSticker', 'GuildSticker', ) if TYPE_CHECKING: import datetime from .state import ConnectionState from .user import User from .guild import Guild from .types.sticker import ( StickerPack as StickerPackPayload, StickerItem as StickerItemPayload, Sticker as StickerPayload, StandardSticker as StandardStickerPayload, GuildSticker as GuildStickerPayload, ListPremiumStickerPacks as ListPremiumStickerPacksPayload, EditGuildSticker, ) class StickerPack(Hashable): """Represents a sticker pack. .. versionadded:: 2.0 .. container:: operations .. describe:: str(x) Returns the name of the sticker pack. .. describe:: x == y Checks if the sticker pack is equal to another sticker pack. .. describe:: x != y Checks if the sticker pack is not equal to another sticker pack. Attributes ----------- name: :class:`str` The name of the sticker pack. description: :class:`str` The description of the sticker pack. id: :class:`int` The id of the sticker pack. stickers: List[:class:`StandardSticker`] The stickers of this sticker pack. sku_id: :class:`int` The SKU ID of the sticker pack. cover_sticker_id: :class:`int` The ID of the sticker used for the cover of the sticker pack. cover_sticker: :class:`StandardSticker` The sticker used for the cover of the sticker pack. """ __slots__ = ( '_state', 'id', 'stickers', 'name', 'sku_id', 'cover_sticker_id', 'cover_sticker', 'description', '_banner', ) def __init__(self, *, state: ConnectionState, data: StickerPackPayload) -> None: self._state: ConnectionState = state self._from_data(data) def _from_data(self, data: StickerPackPayload) -> None: self.id: int = int(data['id']) stickers = data['stickers'] self.stickers: List[StandardSticker] = [StandardSticker(state=self._state, data=sticker) for sticker in stickers] self.name: str = data['name'] self.sku_id: int = int(data['sku_id']) self.cover_sticker_id: int = int(data['cover_sticker_id']) self.cover_sticker: StandardSticker = get(self.stickers, id=self.cover_sticker_id) # type: ignore self.description: str = data['description'] self._banner: int = int(data['banner_asset_id']) @property def banner(self) -> Asset: """:class:`Asset`: The banner asset of the sticker pack.""" return Asset._from_sticker_banner(self._state, self._banner) def __repr__(self) -> str: return f'<StickerPack id={self.id} name={self.name!r} description={self.description!r}>' def __str__(self) -> str: return self.name class _StickerTag(Hashable, AssetMixin): __slots__ = () id: int format: StickerFormatType async def read(self) -> bytes: """|coro| Retrieves the content of this sticker as a :class:`bytes` object. .. note:: Stickers that use the :attr:`StickerFormatType.lottie` format cannot be read. Raises ------ HTTPException Downloading the asset failed. NotFound The asset was deleted. TypeError The sticker is a lottie type. Returns ------- :class:`bytes` The content of the asset. """ if self.format is StickerFormatType.lottie: raise TypeError('Cannot read stickers of format "lottie".') return await super().read() class StickerItem(_StickerTag): """Represents a sticker item. .. versionadded:: 2.0 .. container:: operations .. describe:: str(x) Returns the name of the sticker item. .. describe:: x == y Checks if the sticker item is equal to another sticker item. .. describe:: x != y Checks if the sticker item is not equal to another sticker item. Attributes ----------- name: :class:`str` The sticker's name. id: :class:`int` The id of the sticker. format: :class:`StickerFormatType` The format for the sticker's image. url: :class:`str` The URL for the sticker's image. """ __slots__ = ('_state', 'name', 'id', 'format', 'url') def __init__(self, *, state: ConnectionState, data: StickerItemPayload): self._state: ConnectionState = state self.name: str = data['name'] self.id: int = int(data['id']) 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'<StickerItem id={self.id} name={self.name!r} format={self.format}>' def __str__(self) -> str: return self.name async def fetch(self) -> Union[Sticker, StandardSticker, GuildSticker]: """|coro| Attempts to retrieve the full sticker data of the sticker item. Raises -------- HTTPException Retrieving the sticker failed. Returns -------- Union[:class:`StandardSticker`, :class:`GuildSticker`] The retrieved sticker. """ data: StickerPayload = await self._state.http.get_sticker(self.id) cls, _ = _sticker_factory(data['type']) # type: ignore return cls(state=self._state, data=data) 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 @property 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}>' @cached_slot_property('_cs_guild') 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) 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 elif value == StickerType.guild: return GuildSticker, value else: return Sticker, value
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/sticker.py
sticker.py
import asyncio from collections import namedtuple, deque import concurrent.futures import logging import struct import sys import time import threading import traceback import zlib import aiohttp from . import utils from .activity import BaseActivity from .enums import SpeakingState from .errors import ConnectionClosed, InvalidArgument _log = logging.getLogger(__name__) __all__ = ( 'DiscordWebSocket', 'KeepAliveHandler', 'VoiceKeepAliveHandler', 'DiscordVoiceWebSocket', 'ReconnectWebSocket', ) class ReconnectWebSocket(Exception): """Signals to safely reconnect the websocket.""" def __init__(self, shard_id, *, resume=True): self.shard_id = shard_id self.resume = resume self.op = 'RESUME' if resume else 'IDENTIFY' class WebSocketClosure(Exception): """An exception to make up for the fact that aiohttp doesn't signal closure.""" pass EventListener = namedtuple('EventListener', 'predicate event result future') class GatewayRatelimiter: def __init__(self, count=110, per=60.0): # The default is 110 to give room for at least 10 heartbeats per minute self.max = count self.remaining = count self.window = 0.0 self.per = per self.lock = asyncio.Lock() self.shard_id = None def is_ratelimited(self): current = time.time() if current > self.window + self.per: return False return self.remaining == 0 def get_delay(self): current = time.time() if current > self.window + self.per: self.remaining = self.max if self.remaining == self.max: self.window = current if self.remaining == 0: return self.per - (current - self.window) self.remaining -= 1 if self.remaining == 0: self.window = current return 0.0 async def block(self): async with self.lock: delta = self.get_delay() if delta: _log.warning('WebSocket in shard ID %s is ratelimited, waiting %.2f seconds', self.shard_id, delta) await asyncio.sleep(delta) class KeepAliveHandler(threading.Thread): def __init__(self, *args, **kwargs): ws = kwargs.pop('ws', None) interval = kwargs.pop('interval', None) shard_id = kwargs.pop('shard_id', None) threading.Thread.__init__(self, *args, **kwargs) self.ws = ws self._main_thread_id = ws.thread_id self.interval = interval self.daemon = True self.shard_id = shard_id self.msg = 'Keeping shard ID %s websocket alive with sequence %s.' self.block_msg = 'Shard ID %s heartbeat blocked for more than %s seconds.' self.behind_msg = 'Can\'t keep up, shard ID %s websocket is %.1fs behind.' self._stop_ev = threading.Event() self._last_ack = time.perf_counter() self._last_send = time.perf_counter() self._last_recv = time.perf_counter() self.latency = float('inf') self.heartbeat_timeout = ws._max_heartbeat_timeout def run(self): while not self._stop_ev.wait(self.interval): if self._last_recv + self.heartbeat_timeout < time.perf_counter(): _log.warning("Shard ID %s has stopped responding to the gateway. Closing and restarting.", self.shard_id) coro = self.ws.close(4000) f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop) try: f.result() except Exception: _log.exception('An error occurred while stopping the gateway. Ignoring.') finally: self.stop() return data = self.get_payload() _log.debug(self.msg, self.shard_id, data['d']) coro = self.ws.send_heartbeat(data) f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop) try: # block until sending is complete total = 0 while True: try: f.result(10) break except concurrent.futures.TimeoutError: total += 10 try: frame = sys._current_frames()[self._main_thread_id] except KeyError: msg = self.block_msg else: stack = ''.join(traceback.format_stack(frame)) msg = f'{self.block_msg}\nLoop thread traceback (most recent call last):\n{stack}' _log.warning(msg, self.shard_id, total) except Exception: self.stop() else: self._last_send = time.perf_counter() def get_payload(self): return { 'op': self.ws.HEARTBEAT, 'd': self.ws.sequence } def stop(self): self._stop_ev.set() def tick(self): self._last_recv = time.perf_counter() def ack(self): ack_time = time.perf_counter() self._last_ack = ack_time self.latency = ack_time - self._last_send if self.latency > 10: _log.warning(self.behind_msg, self.shard_id, self.latency) class VoiceKeepAliveHandler(KeepAliveHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.recent_ack_latencies = deque(maxlen=20) self.msg = 'Keeping shard ID %s voice websocket alive with timestamp %s.' self.block_msg = 'Shard ID %s voice heartbeat blocked for more than %s seconds' self.behind_msg = 'High socket latency, shard ID %s heartbeat is %.1fs behind' def get_payload(self): return { 'op': self.ws.HEARTBEAT, 'd': int(time.time() * 1000) } def ack(self): ack_time = time.perf_counter() self._last_ack = ack_time self._last_recv = ack_time self.latency = ack_time - self._last_send self.recent_ack_latencies.append(self.latency) class DiscordClientWebSocketResponse(aiohttp.ClientWebSocketResponse): async def close(self, *, code: int = 4000, message: bytes = b'') -> bool: return await super().close(code=code, message=message) class DiscordWebSocket: """Implements a WebSocket for Discord's gateway v6. Attributes ----------- DISPATCH Receive only. Denotes an event to be sent to Discord, such as READY. HEARTBEAT When received tells Discord to keep the connection alive. When sent asks if your connection is currently alive. IDENTIFY Send only. Starts a new session. PRESENCE Send only. Updates your presence. VOICE_STATE Send only. Starts a new connection to a voice guild. VOICE_PING Send only. Checks ping time to a voice guild, do not use. RESUME Send only. Resumes an existing connection. RECONNECT Receive only. Tells the client to reconnect to a new gateway. REQUEST_MEMBERS Send only. Asks for the full member list of a guild. INVALIDATE_SESSION Receive only. Tells the client to optionally invalidate the session and IDENTIFY again. HELLO Receive only. Tells the client the heartbeat interval. HEARTBEAT_ACK Receive only. Confirms receiving of a heartbeat. Not having it implies a connection issue. GUILD_SYNC Send only. Requests a guild sync. gateway The gateway we are currently connected to. token The authentication token for discord. """ DISPATCH = 0 HEARTBEAT = 1 IDENTIFY = 2 PRESENCE = 3 VOICE_STATE = 4 VOICE_PING = 5 RESUME = 6 RECONNECT = 7 REQUEST_MEMBERS = 8 INVALIDATE_SESSION = 9 HELLO = 10 HEARTBEAT_ACK = 11 GUILD_SYNC = 12 def __init__(self, socket, *, loop): self.socket = socket self.loop = loop # an empty dispatcher to prevent crashes self._dispatch = lambda *args: None # generic event listeners self._dispatch_listeners = [] # the keep alive self._keep_alive = None self.thread_id = threading.get_ident() # ws related stuff self.session_id = None self.sequence = None self._zlib = zlib.decompressobj() self._buffer = bytearray() self._close_code = None self._rate_limiter = GatewayRatelimiter() @property def open(self): return not self.socket.closed def is_ratelimited(self): return self._rate_limiter.is_ratelimited() def debug_log_receive(self, data, /): self._dispatch('socket_raw_receive', data) def log_receive(self, _, /): pass @classmethod async def from_client(cls, client, *, initial=False, gateway=None, shard_id=None, session=None, sequence=None, resume=False): """Creates a main websocket for Discord from a :class:`Client`. This is for internal use only. """ gateway = gateway or await client.http.get_gateway() socket = await client.http.ws_connect(gateway) ws = cls(socket, loop=client.loop) # dynamically add attributes needed ws.token = client.http.token ws._connection = client._connection ws._discord_parsers = client._connection.parsers ws._dispatch = client.dispatch ws.gateway = gateway ws.call_hooks = client._connection.call_hooks ws._initial_identify = initial ws.shard_id = shard_id ws._rate_limiter.shard_id = shard_id ws.shard_count = client._connection.shard_count ws.session_id = session ws.sequence = sequence ws._max_heartbeat_timeout = client._connection.heartbeat_timeout if client._enable_debug_events: ws.send = ws.debug_send ws.log_receive = ws.debug_log_receive client._connection._update_references(ws) _log.debug('Created websocket connected to %s', gateway) # poll event for OP Hello await ws.poll_event() if not resume: await ws.identify() return ws await ws.resume() return ws def wait_for(self, event, predicate, result=None): """Waits for a DISPATCH'd event that meets the predicate. Parameters ----------- event: :class:`str` The event name in all upper case to wait for. predicate A function that takes a data parameter to check for event properties. The data parameter is the 'd' key in the JSON message. result A function that takes the same data parameter and executes to send the result to the future. If ``None``, returns the data. Returns -------- asyncio.Future A future to wait for. """ future = self.loop.create_future() entry = EventListener(event=event, predicate=predicate, result=result, future=future) self._dispatch_listeners.append(entry) return future async def identify(self): """Sends the IDENTIFY packet.""" payload = { 'op': self.IDENTIFY, 'd': { 'token': self.token, 'properties': { '$os': sys.platform, '$browser': 'discord.py', '$device': 'discord.py', '$referrer': '', '$referring_domain': '' }, 'compress': True, 'large_threshold': 250, 'v': 3 } } if self.shard_id is not None and self.shard_count is not None: payload['d']['shard'] = [self.shard_id, self.shard_count] state = self._connection if state._activity is not None or state._status is not None: payload['d']['presence'] = { 'status': state._status, 'game': state._activity, 'since': 0, 'afk': False } if state._intents is not None: payload['d']['intents'] = state._intents.value await self.call_hooks('before_identify', self.shard_id, initial=self._initial_identify) await self.send_as_json(payload) _log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id) async def resume(self): """Sends the RESUME packet.""" payload = { 'op': self.RESUME, 'd': { 'seq': self.sequence, 'session_id': self.session_id, 'token': self.token } } await self.send_as_json(payload) _log.info('Shard ID %s has sent the RESUME payload.', self.shard_id) async def received_message(self, msg, /): if type(msg) is bytes: self._buffer.extend(msg) if len(msg) < 4 or msg[-4:] != b'\x00\x00\xff\xff': return msg = self._zlib.decompress(self._buffer) msg = msg.decode('utf-8') self._buffer = bytearray() self.log_receive(msg) msg = utils._from_json(msg) _log.debug('For Shard ID %s: WebSocket Event: %s', self.shard_id, msg) event = msg.get('t') if event: self._dispatch('socket_event_type', event) op = msg.get('op') data = msg.get('d') seq = msg.get('s') if seq is not None: self.sequence = seq if self._keep_alive: self._keep_alive.tick() if op != self.DISPATCH: if op == self.RECONNECT: # "reconnect" can only be handled by the Client # so we terminate our connection and raise an # internal exception signalling to reconnect. _log.debug('Received RECONNECT opcode.') await self.close() raise ReconnectWebSocket(self.shard_id) if op == self.HEARTBEAT_ACK: if self._keep_alive: self._keep_alive.ack() return if op == self.HEARTBEAT: if self._keep_alive: beat = self._keep_alive.get_payload() await self.send_as_json(beat) return if op == self.HELLO: interval = data['heartbeat_interval'] / 1000.0 self._keep_alive = KeepAliveHandler(ws=self, interval=interval, shard_id=self.shard_id) # send a heartbeat immediately await self.send_as_json(self._keep_alive.get_payload()) self._keep_alive.start() return if op == self.INVALIDATE_SESSION: if data is True: await self.close() raise ReconnectWebSocket(self.shard_id) self.sequence = None self.session_id = None _log.info('Shard ID %s session has been invalidated.', self.shard_id) await self.close(code=1000) raise ReconnectWebSocket(self.shard_id, resume=False) _log.warning('Unknown OP code %s.', op) return if event == 'READY': self._trace = trace = data.get('_trace', []) self.sequence = msg['s'] self.session_id = data['session_id'] # pass back shard ID to ready handler data['__shard_id__'] = self.shard_id _log.info('Shard ID %s has connected to Gateway: %s (Session ID: %s).', self.shard_id, ', '.join(trace), self.session_id) elif event == 'RESUMED': self._trace = trace = data.get('_trace', []) # pass back the shard ID to the resumed handler data['__shard_id__'] = self.shard_id _log.info('Shard ID %s has successfully RESUMED session %s under trace %s.', self.shard_id, self.session_id, ', '.join(trace)) try: func = self._discord_parsers[event] except KeyError: _log.debug('Unknown event %s.', event) else: func(data) # remove the dispatched listeners removed = [] for index, entry in enumerate(self._dispatch_listeners): if entry.event != event: continue future = entry.future if future.cancelled(): removed.append(index) continue try: valid = entry.predicate(data) except Exception as exc: future.set_exception(exc) removed.append(index) else: if valid: ret = data if entry.result is None else entry.result(data) future.set_result(ret) removed.append(index) for index in reversed(removed): del self._dispatch_listeners[index] @property def latency(self): """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.""" heartbeat = self._keep_alive return float('inf') if heartbeat is None else heartbeat.latency def _can_handle_close(self): code = self._close_code or self.socket.close_code return code not in (1000, 4004, 4010, 4011, 4012, 4013, 4014) async def poll_event(self): """Polls for a DISPATCH event and handles the general gateway loop. Raises ------ ConnectionClosed The websocket connection was terminated for unhandled reasons. """ try: msg = await self.socket.receive(timeout=self._max_heartbeat_timeout) if msg.type is aiohttp.WSMsgType.TEXT: await self.received_message(msg.data) elif msg.type is aiohttp.WSMsgType.BINARY: await self.received_message(msg.data) elif msg.type is aiohttp.WSMsgType.ERROR: _log.debug('Received %s', msg) raise msg.data elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSING, aiohttp.WSMsgType.CLOSE): _log.debug('Received %s', msg) raise WebSocketClosure except (asyncio.TimeoutError, WebSocketClosure) as e: # Ensure the keep alive handler is closed if self._keep_alive: self._keep_alive.stop() self._keep_alive = None if isinstance(e, asyncio.TimeoutError): _log.info('Timed out receiving packet. Attempting a reconnect.') raise ReconnectWebSocket(self.shard_id) from None code = self._close_code or self.socket.close_code if self._can_handle_close(): _log.info('Websocket closed with %s, attempting a reconnect.', code) raise ReconnectWebSocket(self.shard_id) from None else: _log.info('Websocket closed with %s, cannot reconnect.', code) raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None async def debug_send(self, data, /): await self._rate_limiter.block() self._dispatch('socket_raw_send', data) await self.socket.send_str(data) async def send(self, data, /): await self._rate_limiter.block() await self.socket.send_str(data) async def send_as_json(self, data): try: await self.send(utils._to_json(data)) except RuntimeError as exc: if not self._can_handle_close(): raise ConnectionClosed(self.socket, shard_id=self.shard_id) from exc async def send_heartbeat(self, data): # This bypasses the rate limit handling code since it has a higher priority try: await self.socket.send_str(utils._to_json(data)) except RuntimeError as exc: if not self._can_handle_close(): raise ConnectionClosed(self.socket, shard_id=self.shard_id) from exc async def change_presence(self, *, activity=None, status=None, since=0.0): if activity is not None: if not isinstance(activity, BaseActivity): raise InvalidArgument('activity must derive from BaseActivity.') activity = [activity.to_dict()] else: activity = [] if status == 'idle': since = int(time.time() * 1000) payload = { 'op': self.PRESENCE, 'd': { 'activities': activity, 'afk': False, 'since': since, 'status': status } } sent = utils._to_json(payload) _log.debug('Sending "%s" to change status', sent) await self.send(sent) async def request_chunks(self, guild_id, query=None, *, limit, user_ids=None, presences=False, nonce=None): payload = { 'op': self.REQUEST_MEMBERS, 'd': { 'guild_id': guild_id, 'presences': presences, 'limit': limit } } if nonce: payload['d']['nonce'] = nonce if user_ids: payload['d']['user_ids'] = user_ids if query is not None: payload['d']['query'] = query await self.send_as_json(payload) async def voice_state(self, guild_id, channel_id, self_mute=False, self_deaf=False): payload = { 'op': self.VOICE_STATE, 'd': { 'guild_id': guild_id, 'channel_id': channel_id, 'self_mute': self_mute, 'self_deaf': self_deaf } } _log.debug('Updating our voice state to %s.', payload) await self.send_as_json(payload) async def close(self, code=4000): if self._keep_alive: self._keep_alive.stop() self._keep_alive = None self._close_code = code await self.socket.close(code=code) class DiscordVoiceWebSocket: """Implements the websocket protocol for handling voice connections. Attributes ----------- IDENTIFY Send only. Starts a new voice session. SELECT_PROTOCOL Send only. Tells discord what encryption mode and how to connect for voice. READY Receive only. Tells the websocket that the initial connection has completed. HEARTBEAT Send only. Keeps your websocket connection alive. SESSION_DESCRIPTION Receive only. Gives you the secret key required for voice. SPEAKING Send only. Notifies the client if you are currently speaking. HEARTBEAT_ACK Receive only. Tells you your heartbeat has been acknowledged. RESUME Sent only. Tells the client to resume its session. HELLO Receive only. Tells you that your websocket connection was acknowledged. RESUMED Sent only. Tells you that your RESUME request has succeeded. CLIENT_CONNECT Indicates a user has connected to voice. CLIENT_DISCONNECT Receive only. Indicates a user has disconnected from voice. """ IDENTIFY = 0 SELECT_PROTOCOL = 1 READY = 2 HEARTBEAT = 3 SESSION_DESCRIPTION = 4 SPEAKING = 5 HEARTBEAT_ACK = 6 RESUME = 7 HELLO = 8 RESUMED = 9 CLIENT_CONNECT = 12 CLIENT_DISCONNECT = 13 def __init__(self, socket, loop, *, hook=None): self.ws = socket self.loop = loop self._keep_alive = None self._close_code = None self.secret_key = None if hook: self._hook = hook async def _hook(self, *args): pass async def send_as_json(self, data): _log.debug('Sending voice websocket frame: %s.', data) await self.ws.send_str(utils._to_json(data)) send_heartbeat = send_as_json async def resume(self): state = self._connection payload = { 'op': self.RESUME, 'd': { 'token': state.token, 'server_id': str(state.server_id), 'session_id': state.session_id } } await self.send_as_json(payload) async def identify(self): state = self._connection payload = { 'op': self.IDENTIFY, 'd': { 'server_id': str(state.server_id), 'user_id': str(state.user.id), 'session_id': state.session_id, 'token': state.token } } await self.send_as_json(payload) @classmethod async def from_client(cls, client, *, resume=False, hook=None): """Creates a voice websocket for the :class:`VoiceClient`.""" gateway = 'wss://' + client.endpoint + '/?v=4' http = client._state.http socket = await http.ws_connect(gateway, compress=15) ws = cls(socket, loop=client.loop, hook=hook) ws.gateway = gateway ws._connection = client ws._max_heartbeat_timeout = 60.0 ws.thread_id = threading.get_ident() if resume: await ws.resume() else: await ws.identify() return ws async def select_protocol(self, ip, port, mode): payload = { 'op': self.SELECT_PROTOCOL, 'd': { 'protocol': 'udp', 'data': { 'address': ip, 'port': port, 'mode': mode } } } await self.send_as_json(payload) async def client_connect(self): payload = { 'op': self.CLIENT_CONNECT, 'd': { 'audio_ssrc': self._connection.ssrc } } await self.send_as_json(payload) async def speak(self, state=SpeakingState.voice): payload = { 'op': self.SPEAKING, 'd': { 'speaking': int(state), 'delay': 0 } } await self.send_as_json(payload) async def received_message(self, msg): _log.debug('Voice websocket frame received: %s', msg) op = msg['op'] data = msg.get('d') if op == self.READY: await self.initial_connection(data) elif op == self.HEARTBEAT_ACK: self._keep_alive.ack() elif op == self.RESUMED: _log.info('Voice RESUME succeeded.') elif op == self.SESSION_DESCRIPTION: self._connection.mode = data['mode'] await self.load_secret_key(data) elif op == self.HELLO: interval = data['heartbeat_interval'] / 1000.0 self._keep_alive = VoiceKeepAliveHandler(ws=self, interval=min(interval, 5.0)) self._keep_alive.start() await self._hook(self, msg) async def initial_connection(self, data): state = self._connection state.ssrc = data['ssrc'] state.voice_port = data['port'] state.endpoint_ip = data['ip'] packet = bytearray(70) struct.pack_into('>H', packet, 0, 1) # 1 = Send struct.pack_into('>H', packet, 2, 70) # 70 = Length struct.pack_into('>I', packet, 4, state.ssrc) state.socket.sendto(packet, (state.endpoint_ip, state.voice_port)) recv = await self.loop.sock_recv(state.socket, 70) _log.debug('received packet in initial_connection: %s', recv) # the ip is ascii starting at the 4th byte and ending at the first null ip_start = 4 ip_end = recv.index(0, ip_start) state.ip = recv[ip_start:ip_end].decode('ascii') state.port = struct.unpack_from('>H', recv, len(recv) - 2)[0] _log.debug('detected ip: %s port: %s', state.ip, state.port) # there *should* always be at least one supported mode (xsalsa20_poly1305) modes = [mode for mode in data['modes'] if mode in self._connection.supported_modes] _log.debug('received supported encryption modes: %s', ", ".join(modes)) mode = modes[0] await self.select_protocol(state.ip, state.port, mode) _log.info('selected the voice protocol for use (%s)', mode) @property def latency(self): """:class:`float`: Latency between a HEARTBEAT and its HEARTBEAT_ACK in seconds.""" heartbeat = self._keep_alive return float('inf') if heartbeat is None else heartbeat.latency @property def average_latency(self): """:class:`list`: Average of last 20 HEARTBEAT latencies.""" heartbeat = self._keep_alive if heartbeat is None or not heartbeat.recent_ack_latencies: return float('inf') return sum(heartbeat.recent_ack_latencies) / len(heartbeat.recent_ack_latencies) async def load_secret_key(self, data): _log.info('received secret key for voice connection') self.secret_key = self._connection.secret_key = data.get('secret_key') await self.speak() await self.speak(False) async def poll_event(self): # This exception is handled up the chain msg = await asyncio.wait_for(self.ws.receive(), timeout=30.0) if msg.type is aiohttp.WSMsgType.TEXT: await self.received_message(utils._from_json(msg.data)) elif msg.type is aiohttp.WSMsgType.ERROR: _log.debug('Received %s', msg) raise ConnectionClosed(self.ws, shard_id=None) from msg.data elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSING): _log.debug('Received %s', msg) raise ConnectionClosed(self.ws, shard_id=None, code=self._close_code) async def close(self, code=1000): if self._keep_alive is not None: self._keep_alive.stop() self._close_code = code await self.ws.close(code=code)
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/gateway.py
gateway.py
import colorsys import random from typing import ( Any, Optional, Tuple, Type, TypeVar, Union, ) __all__ = ( 'Colour', 'Color', ) CT = TypeVar('CT', bound='Colour') class Colour: """Represents a Discord role colour. This class is similar to a (red, green, blue) :class:`tuple`. There is an alias for this called Color. .. container:: operations .. describe:: x == y Checks if two colours are equal. .. describe:: x != y Checks if two colours are not equal. .. describe:: hash(x) Return the colour's hash. .. describe:: str(x) Returns the hex format for the colour. .. describe:: int(x) Returns the raw colour value. Attributes ------------ value: :class:`int` The raw integer colour value. """ __slots__ = ('value',) def __init__(self, value: int): if not isinstance(value, int): raise TypeError(f'Expected int parameter, received {value.__class__.__name__} instead.') self.value: int = value def _get_byte(self, byte: int) -> int: return (self.value >> (8 * byte)) & 0xff def __eq__(self, other: Any) -> bool: return isinstance(other, Colour) and self.value == other.value def __ne__(self, other: Any) -> bool: return not self.__eq__(other) def __str__(self) -> str: return f'#{self.value:0>6x}' def __int__(self) -> int: return self.value def __repr__(self) -> str: return f'<Colour value={self.value}>' def __hash__(self) -> int: return hash(self.value) @property def r(self) -> int: """:class:`int`: Returns the red component of the colour.""" return self._get_byte(2) @property def g(self) -> int: """:class:`int`: Returns the green component of the colour.""" return self._get_byte(1) @property def b(self) -> int: """:class:`int`: Returns the blue component of the colour.""" return self._get_byte(0) def to_rgb(self) -> Tuple[int, int, int]: """Tuple[:class:`int`, :class:`int`, :class:`int`]: Returns an (r, g, b) tuple representing the colour.""" return (self.r, self.g, self.b) @classmethod def from_rgb(cls: Type[CT], r: int, g: int, b: int) -> CT: """Constructs a :class:`Colour` from an RGB tuple.""" return cls((r << 16) + (g << 8) + b) @classmethod def from_hsv(cls: Type[CT], h: float, s: float, v: float) -> CT: """Constructs a :class:`Colour` from an HSV tuple.""" rgb = colorsys.hsv_to_rgb(h, s, v) return cls.from_rgb(*(int(x * 255) for x in rgb)) @classmethod def default(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0``.""" return cls(0) @classmethod def random(cls: Type[CT], *, seed: Optional[Union[int, str, float, bytes, bytearray]] = None) -> CT: """A factory method that returns a :class:`Colour` with a random hue. .. note:: The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value. .. versionadded:: 1.6 Parameters ------------ seed: Optional[Union[:class:`int`, :class:`str`, :class:`float`, :class:`bytes`, :class:`bytearray`]] The seed to initialize the RNG with. If ``None`` is passed the default RNG is used. .. versionadded:: 1.7 """ rand = random if seed is None else random.Random(seed) return cls.from_hsv(rand.random(), 1, 1) @classmethod def teal(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x1abc9c``.""" return cls(0x1abc9c) @classmethod def dark_teal(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x11806a``.""" return cls(0x11806a) @classmethod def brand_green(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x57F287``. .. versionadded:: 2.0 """ return cls(0x57F287) @classmethod def green(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x2ecc71``.""" return cls(0x2ecc71) @classmethod def dark_green(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x1f8b4c``.""" return cls(0x1f8b4c) @classmethod def blue(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x3498db``.""" return cls(0x3498db) @classmethod def dark_blue(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x206694``.""" return cls(0x206694) @classmethod def purple(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x9b59b6``.""" return cls(0x9b59b6) @classmethod def dark_purple(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x71368a``.""" return cls(0x71368a) @classmethod def magenta(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xe91e63``.""" return cls(0xe91e63) @classmethod def dark_magenta(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xad1457``.""" return cls(0xad1457) @classmethod def gold(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xf1c40f``.""" return cls(0xf1c40f) @classmethod def dark_gold(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xc27c0e``.""" return cls(0xc27c0e) @classmethod def orange(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xe67e22``.""" return cls(0xe67e22) @classmethod def dark_orange(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xa84300``.""" return cls(0xa84300) @classmethod def brand_red(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xED4245``. .. versionadded:: 2.0 """ return cls(0xED4245) @classmethod def red(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xe74c3c``.""" return cls(0xe74c3c) @classmethod def dark_red(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x992d22``.""" return cls(0x992d22) @classmethod def lighter_grey(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x95a5a6``.""" return cls(0x95a5a6) lighter_gray = lighter_grey @classmethod def dark_grey(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x607d8b``.""" return cls(0x607d8b) dark_gray = dark_grey @classmethod def light_grey(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x979c9f``.""" return cls(0x979c9f) light_gray = light_grey @classmethod def darker_grey(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x546e7a``.""" return cls(0x546e7a) darker_gray = darker_grey @classmethod def og_blurple(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x7289da``.""" return cls(0x7289da) @classmethod def blurple(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x5865F2``.""" return cls(0x5865F2) @classmethod def greyple(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x99aab5``.""" return cls(0x99aab5) @classmethod def dark_theme(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0x36393F``. This will appear transparent on Discord's dark theme. .. versionadded:: 1.5 """ return cls(0x36393F) @classmethod def fuchsia(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xEB459E``. .. versionadded:: 2.0 """ return cls(0xEB459E) @classmethod def yellow(cls: Type[CT]) -> CT: """A factory method that returns a :class:`Colour` with a value of ``0xFEE75C``. .. versionadded:: 2.0 """ return cls(0xFEE75C) Color = Colour
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/colour.py
colour.py
from __future__ import annotations from typing import Any, Callable, ClassVar, Dict, Iterator, List, Optional, Sequence, TYPE_CHECKING, Tuple from functools import partial from itertools import groupby import traceback import asyncio import sys import time import os from .item import Item, ItemCallbackType from ..components import ( Component, ActionRow as ActionRowComponent, _component_factory, Button as ButtonComponent, SelectMenu as SelectComponent, ) __all__ = ( 'View', ) if TYPE_CHECKING: from ..interactions import Interaction from ..message import Message from ..types.components import Component as ComponentPayload from ..state import ConnectionState def _walk_all_components(components: List[Component]) -> Iterator[Component]: for item in components: if isinstance(item, ActionRowComponent): yield from item.children else: yield item 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) return Item.from_component(component) class _ViewWeights: __slots__ = ( 'weights', ) def __init__(self, children: List[Item]): self.weights: List[int] = [0, 0, 0, 0, 0] key = lambda i: sys.maxsize if i.row is None else i.row children = sorted(children, key=key) for row, group in groupby(children, key=key): for item in group: self.add_item(item) def find_open_space(self, item: Item) -> int: for index, weight in enumerate(self.weights): if weight + item.width <= 5: return index raise ValueError('could not find open space for item') def add_item(self, item: Item) -> None: if item.row is not None: total = self.weights[item.row] + item.width if total > 5: raise ValueError(f'item would not fit at row {item.row} ({total} > 5 width)') self.weights[item.row] = total item._rendered_row = item.row else: index = self.find_open_space(item) self.weights[index] += item.width item._rendered_row = index def remove_item(self, item: Item) -> None: if item._rendered_row is not None: self.weights[item._rendered_row] -= item.width item._rendered_row = None def clear(self) -> None: self.weights = [0, 0, 0, 0, 0] class View: """Represents a UI view. This object must be inherited to create a UI within Discord. .. versionadded:: 2.0 Parameters ----------- timeout: Optional[:class:`float`] Timeout in seconds from last interaction with the UI before no longer accepting input. If ``None`` then there is no timeout. Attributes ------------ timeout: Optional[:class:`float`] Timeout from last interaction with the UI before no longer accepting input. If ``None`` then there is no timeout. children: List[:class:`Item`] The list of children attached to this view. """ __discord_ui_view__: ClassVar[bool] = True __view_children_items__: ClassVar[List[ItemCallbackType]] = [] def __init_subclass__(cls) -> None: children: List[ItemCallbackType] = [] for base in reversed(cls.__mro__): for member in base.__dict__.values(): if hasattr(member, '__discord_ui_model_type__'): children.append(member) if len(children) > 25: raise TypeError('View cannot have more than 25 children') cls.__view_children_items__ = children def __init__(self, *, timeout: Optional[float] = 180.0): self.timeout = timeout self.children: List[Item] = [] for func in self.__view_children_items__: item: Item = func.__discord_ui_model_type__(**func.__discord_ui_model_kwargs__) item.callback = partial(func, self, item) item._view = self setattr(self, func.__name__, item) self.children.append(item) self.__weights = _ViewWeights(self.children) loop = asyncio.get_running_loop() self.id: str = os.urandom(16).hex() self.__cancel_callback: Optional[Callable[[View], None]] = None self.__timeout_expiry: Optional[float] = None self.__timeout_task: Optional[asyncio.Task[None]] = None self.__stopped: asyncio.Future[bool] = loop.create_future() def __repr__(self) -> str: return f'<{self.__class__.__name__} timeout={self.timeout} children={len(self.children)}>' async def __timeout_task_impl(self) -> None: while True: # Guard just in case someone changes the value of the timeout at runtime if self.timeout is None: return if self.__timeout_expiry is None: return self._dispatch_timeout() # Check if we've elapsed our currently set timeout now = time.monotonic() if now >= self.__timeout_expiry: return self._dispatch_timeout() # Wait N seconds to see if timeout data has been refreshed await asyncio.sleep(self.__timeout_expiry - now) def to_components(self) -> List[Dict[str, Any]]: def key(item: Item) -> int: return item._rendered_row or 0 children = sorted(self.children, key=key) components: List[Dict[str, Any]] = [] for _, group in groupby(children, key=key): children = [item.to_component_dict() for item in group] if not children: continue components.append( { 'type': 1, 'components': children, } ) return components @classmethod def from_message(cls, message: Message, /, *, timeout: Optional[float] = 180.0) -> View: """Converts a message's components into a :class:`View`. The :attr:`.Message.components` of a message are read-only and separate types from those in the ``discord.ui`` namespace. In order to modify and edit message components they must be converted into a :class:`View` first. Parameters ----------- message: :class:`discord.Message` The message with components to convert into a view. timeout: Optional[:class:`float`] The timeout of the converted view. Returns -------- :class:`View` The converted view. This always returns a :class:`View` and not one of its subclasses. """ view = View(timeout=timeout) for component in _walk_all_components(message.components): view.add_item(_component_to_item(component)) return view @property def _expires_at(self) -> Optional[float]: if self.timeout: return time.monotonic() + self.timeout return None def add_item(self, item: Item) -> None: """Adds an item to the view. Parameters ----------- item: :class:`Item` The item to add to the view. Raises -------- TypeError An :class:`Item` was not passed. ValueError Maximum number of children has been exceeded (25) or the row the item is trying to be added to is full. """ if len(self.children) > 25: raise ValueError('maximum number of children exceeded') if not isinstance(item, Item): raise TypeError(f'expected Item not {item.__class__!r}') self.__weights.add_item(item) item._view = self self.children.append(item) def remove_item(self, item: Item) -> None: """Removes an item from the view. Parameters ----------- item: :class:`Item` The item to remove from the view. """ try: self.children.remove(item) except ValueError: pass else: self.__weights.remove_item(item) def clear_items(self) -> None: """Removes all items from the view.""" self.children.clear() self.__weights.clear() async def interaction_check(self, interaction: Interaction) -> bool: """|coro| A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction. This is useful to override if, for example, you want to ensure that the interaction author is a given user. The default implementation of this returns ``True``. .. note:: If an exception occurs within the body then the check is considered a failure and :meth:`on_error` is called. Parameters ----------- interaction: :class:`~discord.Interaction` The interaction that occurred. Returns --------- :class:`bool` Whether the view children's callbacks should be called. """ return True async def on_timeout(self) -> None: """|coro| A callback that is called when a view's timeout elapses without being explicitly stopped. """ pass async def on_error(self, error: Exception, item: Item, interaction: Interaction) -> None: """|coro| A callback that is called when an item's callback or :meth:`interaction_check` fails with an error. The default implementation prints the traceback to stderr. Parameters ----------- error: :class:`Exception` The exception that was raised. item: :class:`Item` The item that failed the dispatch. interaction: :class:`~discord.Interaction` The interaction that led to the failure. """ print(f'Ignoring exception in view {self} for item {item}:', file=sys.stderr) traceback.print_exception(error.__class__, error, error.__traceback__, file=sys.stderr) async def _scheduled_task(self, item: Item, interaction: Interaction): try: if self.timeout: self.__timeout_expiry = time.monotonic() + self.timeout allow = await self.interaction_check(interaction) if not allow: return await item.callback(interaction) if not interaction.response._responded: await interaction.response.defer() except Exception as e: return await self.on_error(e, item, interaction) def _start_listening_from_store(self, store: ViewStore) -> None: self.__cancel_callback = partial(store.remove_view) if self.timeout: loop = asyncio.get_running_loop() if self.__timeout_task is not None: self.__timeout_task.cancel() self.__timeout_expiry = time.monotonic() + self.timeout self.__timeout_task = loop.create_task(self.__timeout_task_impl()) def _dispatch_timeout(self): if self.__stopped.done(): return self.__stopped.set_result(True) asyncio.create_task(self.on_timeout(), name=f'discord-ui-view-timeout-{self.id}') def _dispatch_item(self, item: Item, interaction: Interaction): if self.__stopped.done(): return asyncio.create_task(self._scheduled_task(item, interaction), name=f'discord-ui-view-dispatch-{self.id}') def refresh(self, components: List[Component]): # This is pretty hacky at the moment # fmt: off old_state: Dict[Tuple[int, str], Item] = { (item.type.value, item.custom_id): item # type: ignore for item in self.children if item.is_dispatchable() } # fmt: on children: List[Item] = [] for component in _walk_all_components(components): try: older = old_state[(component.type.value, component.custom_id)] # type: ignore except (KeyError, AttributeError): children.append(_component_to_item(component)) else: older.refresh_component(component) children.append(older) self.children = children def stop(self) -> None: """Stops listening to interaction events from this view. This operation cannot be undone. """ if not self.__stopped.done(): self.__stopped.set_result(False) self.__timeout_expiry = None if self.__timeout_task is not None: self.__timeout_task.cancel() self.__timeout_task = None if self.__cancel_callback: self.__cancel_callback(self) self.__cancel_callback = None def is_finished(self) -> bool: """:class:`bool`: Whether the view has finished interacting.""" return self.__stopped.done() def is_dispatching(self) -> bool: """:class:`bool`: Whether the view has been added for dispatching purposes.""" return self.__cancel_callback is not None def is_persistent(self) -> bool: """:class:`bool`: Whether the view is set up as persistent. A persistent view has all their components with a set ``custom_id`` and a :attr:`timeout` set to ``None``. """ return self.timeout is None and all(item.is_persistent() for item in self.children) async def wait(self) -> bool: """Waits until the view has finished interacting. A view is considered finished when :meth:`stop` is called or it times out. Returns -------- :class:`bool` If ``True``, then the view timed out. If ``False`` then the view finished normally. """ return await self.__stopped class ViewStore: def __init__(self, state: ConnectionState): # (component_type, message_id, custom_id): (View, Item) self._views: Dict[Tuple[int, Optional[int], str], Tuple[View, Item]] = {} # message_id: View self._synced_message_views: Dict[int, View] = {} self._state: ConnectionState = state @property def persistent_views(self) -> Sequence[View]: # fmt: off views = { view.id: view for (_, (view, _)) in self._views.items() if view.is_persistent() } # fmt: on return list(views.values()) def __verify_integrity(self): to_remove: List[Tuple[int, Optional[int], str]] = [] for (k, (view, _)) in self._views.items(): if view.is_finished(): to_remove.append(k) for k in to_remove: del self._views[k] def add_view(self, view: View, message_id: Optional[int] = None): self.__verify_integrity() view._start_listening_from_store(self) for item in view.children: if item.is_dispatchable(): self._views[(item.type.value, message_id, item.custom_id)] = (view, item) # type: ignore if message_id is not None: self._synced_message_views[message_id] = view def remove_view(self, view: View): for item in view.children: if item.is_dispatchable(): self._views.pop((item.type.value, item.custom_id), None) # type: ignore for key, value in self._synced_message_views.items(): if value.id == view.id: del self._synced_message_views[key] break def dispatch(self, component_type: int, custom_id: str, interaction: Interaction): self.__verify_integrity() message_id: Optional[int] = interaction.message and interaction.message.id key = (component_type, message_id, custom_id) # Fallback to None message_id searches in case a persistent view # was added without an associated message_id value = self._views.get(key) or self._views.get((component_type, None, custom_id)) if value is None: return view, item = value item.refresh_state(interaction) view._dispatch_item(item, interaction) def is_message_tracked(self, message_id: int): return message_id in self._synced_message_views def remove_message_tracking(self, message_id: int) -> Optional[View]: return self._synced_message_views.pop(message_id, None) def update_from_message(self, message_id: int, components: List[ComponentPayload]): # pre-req: is_message_tracked == true view = self._synced_message_views[message_id] view.refresh([_component_factory(d) for d in components])
zarenacord.py
/zarenacord.py-2.0.0-py3-none-any.whl/discord/ui/view.py
view.py