text
stringlengths
81
112k
|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. async def webhooks(self): """|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. """ data = await self._state.http.channel_webhooks(self.id) return [Webhook.from_state(d, state=self._state) for d in data]
|coro| Creates a webhook for this channel. Requires :attr:`~.Permissions.manage_webhooks` permissions. .. versionchanged:: 1.1.0 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. async def create_webhook(self, *, name, avatar=None, reason=None): """|coro| Creates a webhook for this channel. Requires :attr:`~.Permissions.manage_webhooks` permissions. .. versionchanged:: 1.1.0 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. """ if avatar is not None: avatar = utils._bytes_to_base64_data(avatar) data = await self._state.http.create_webhook(self.id, name=str(name), avatar=avatar, reason=reason) return Webhook.from_state(data, state=self._state)
Returns a list of :class:`Member` that are currently inside this voice channel. def members(self): """Returns a list of :class:`Member` that are currently inside this voice channel.""" ret = [] for user_id, state in self.guild._voice_states.items(): if state.channel.id == self.id: member = self.guild.get_member(user_id) if member is not None: ret.append(member) return ret
|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. 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. 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. async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. 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. 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. """ try: position = options.pop('position') except KeyError: pass else: await self._move(position, reason=reason) self.position = position if options: data = await self._state.http.edit_channel(self.id, reason=reason, **options) self._update(self.guild, data)
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 channels(self): """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
List[:class:`TextChannel`]: Returns the text channels that are under this category. def text_channels(self): """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
List[:class:`VoiceChannel`]: Returns the voice channels that are under this category. def voice_channels(self): """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
|coro| A shortcut method to :meth:`Guild.create_text_channel` to create a :class:`TextChannel` in the category. async def create_text_channel(self, name, *, overwrites=None, reason=None, **options): """|coro| A shortcut method to :meth:`Guild.create_text_channel` to create a :class:`TextChannel` in the category. """ return await self.guild.create_text_channel(name, overwrites=overwrites, category=self, reason=reason, **options)
|coro| A shortcut method to :meth:`Guild.create_voice_channel` to create a :class:`VoiceChannel` in the category. async def create_voice_channel(self, name, *, overwrites=None, reason=None, **options): """|coro| A shortcut method to :meth:`Guild.create_voice_channel` to create a :class:`VoiceChannel` in the category. """ return await self.guild.create_voice_channel(name, overwrites=overwrites, category=self, reason=reason, **options)
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: - send_tts_messages: You cannot send TTS messages in a DM. - manage_messages: You cannot delete others messages in a DM. Parameters ----------- user: :class:`User` The user to check permissions for. This parameter is ignored but kept for compatibility. Returns -------- :class:`Permissions` The resolved permissions. def permissions_for(self, user=None): """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: - send_tts_messages: You cannot send TTS messages in a DM. - manage_messages: You cannot delete others messages in a DM. Parameters ----------- user: :class:`User` The user to check permissions for. This parameter is ignored but kept for compatibility. Returns -------- :class:`Permissions` The resolved permissions. """ base = Permissions.text() base.send_tts_messages = False base.manage_messages = False return base
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: - send_tts_messages: You cannot send TTS messages in a DM. - manage_messages: You cannot delete others messages in a DM. This also checks the kick_members permission if the user is the owner. Parameters ----------- user: :class:`User` The user to check permissions for. Returns -------- :class:`Permissions` The resolved permissions for the user. def permissions_for(self, user): """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: - send_tts_messages: You cannot send TTS messages in a DM. - manage_messages: You cannot delete others messages in a DM. This also checks the kick_members permission if the user is the owner. Parameters ----------- user: :class:`User` The user to check permissions for. Returns -------- :class:`Permissions` The resolved permissions for the user. """ base = Permissions.text() base.send_tts_messages = False base.manage_messages = False base.mention_everyone = True if user.id == self.owner.id: base.kick_members = True return base
r"""|coro| Adds recipients to this group. A group can only have a maximum of 10 members. Attempting to add more ends up in an exception. To add a recipient to the group, you must have a relationship with the user of type :attr:`RelationshipType.friend`. Parameters ----------- \*recipients: :class:`User` An argument list of users to add to this group. Raises ------- HTTPException Adding a recipient to this group failed. async def add_recipients(self, *recipients): r"""|coro| Adds recipients to this group. A group can only have a maximum of 10 members. Attempting to add more ends up in an exception. To add a recipient to the group, you must have a relationship with the user of type :attr:`RelationshipType.friend`. Parameters ----------- \*recipients: :class:`User` An argument list of users to add to this group. Raises ------- HTTPException Adding a recipient to this group failed. """ # TODO: wait for the corresponding WS event req = self._state.http.add_group_recipient for recipient in recipients: await req(self.id, recipient.id)
r"""|coro| Removes recipients from this group. Parameters ----------- \*recipients: :class:`User` An argument list of users to remove from this group. Raises ------- HTTPException Removing a recipient from this group failed. async def remove_recipients(self, *recipients): r"""|coro| Removes recipients from this group. Parameters ----------- \*recipients: :class:`User` An argument list of users to remove from this group. Raises ------- HTTPException Removing a recipient from this group failed. """ # TODO: wait for the corresponding WS event req = self._state.http.remove_group_recipient for recipient in recipients: await req(self.id, recipient.id)
|coro| Edits the group. Parameters ----------- name: Optional[:class:`str`] The new name to change the group to. Could be ``None`` to remove the name. icon: Optional[:class:`bytes`] A :term:`py:bytes-like object` representing the new icon. Could be ``None`` to remove the icon. Raises ------- HTTPException Editing the group failed. async def edit(self, **fields): """|coro| Edits the group. Parameters ----------- name: Optional[:class:`str`] The new name to change the group to. Could be ``None`` to remove the name. icon: Optional[:class:`bytes`] A :term:`py:bytes-like object` representing the new icon. Could be ``None`` to remove the icon. Raises ------- HTTPException Editing the group failed. """ try: icon_bytes = fields['icon'] except KeyError: pass else: if icon_bytes is not None: fields['icon'] = utils._bytes_to_base64_data(icon_bytes) data = await self._state.http.edit_group(self.id, **fields) self._update_group(data)
Returns a :class:`list` of :class:`Roles` that have been overridden from their default values in the :attr:`Guild.roles` attribute. def changed_roles(self): """Returns a :class:`list` of :class:`Roles` that have been overridden from their default values in the :attr:`Guild.roles` attribute.""" ret = [] g = self.guild for overwrite in filter(lambda o: o.type == '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
Returns the channel-specific overwrites for a member or a role. Parameters ----------- obj The :class:`Role` or :class:`abc.User` denoting whose overwrite to get. Returns --------- :class:`PermissionOverwrite` The permission overwrites for this object. def overwrites_for(self, obj): """Returns the channel-specific overwrites for a member or a role. Parameters ----------- obj The :class:`Role` or :class:`abc.User` denoting whose overwrite to get. Returns --------- :class:`PermissionOverwrite` The permission overwrites for this object. """ if isinstance(obj, User): predicate = lambda p: p.type == 'member' elif isinstance(obj, Role): predicate = lambda p: p.type == '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()
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:`Role` or a :class:`Member` and the key is the overwrite as a :class:`PermissionOverwrite`. Returns -------- Mapping[Union[:class:`Role`, :class:`Member`], :class:`PermissionOverwrite`]: The channel's permission overwrites. def overwrites(self): """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:`Role` or a :class:`Member` and the key is the overwrite as a :class:`PermissionOverwrite`. Returns -------- Mapping[Union[:class:`Role`, :class:`Member`], :class:`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) if ow.type == 'role': target = self.guild.get_role(ow.id) elif ow.type == '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
Handles permission resolution for the current :class:`Member`. This function takes into consideration the following cases: - Guild owner - Guild roles - Channel overrides - Member overrides Parameters ---------- member: :class:`Member` The member to resolve permissions for. Returns ------- :class:`Permissions` The resolved permissions for the member. def permissions_for(self, member): """Handles permission resolution for the current :class:`Member`. This function takes into consideration the following cases: - Guild owner - Guild roles - Channel overrides - Member overrides Parameters ---------- member: :class:`Member` The member to resolve permissions for. Returns ------- :class:`Permissions` The resolved permissions for the member. """ # 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. o = self.guild.owner if o is not None and member.id == o.id: return Permissions.all() default = self.guild.default_role base = Permissions(default.permissions.value) roles = member.roles # Apply guild roles that the member has. for role in roles: base.value |= role.permissions.value # 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 # not sure if doing member._roles.get(...) is better than the # set approach. While this is O(N) to re-create into a set for O(1) # the direct approach would just be O(log n) for searching with no # extra memory overhead. For now, I'll keep the set cast # Note that the member.roles accessor up top also creates a # temporary list member_role_ids = {r.id for r in roles} denies = 0 allows = 0 # Apply channel specific role permission overwrites for overwrite in remaining_overwrites: if overwrite.type == 'role' and overwrite.id in member_role_ids: 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.type == 'member' and overwrite.id == member.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
|coro| Deletes the channel. You must have :attr:`~.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 ------- Forbidden You do not have proper permissions to delete the channel. NotFound The channel was not found or was already deleted. HTTPException Deleting the channel failed. async def delete(self, *, reason=None): """|coro| Deletes the channel. You must have :attr:`~.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 ------- Forbidden You do not have proper permissions to delete the channel. NotFound The channel was not found or was already deleted. HTTPException Deleting the channel failed. """ await self._state.http.delete_channel(self.id, reason=reason)
r"""|coro| Sets the channel specific permission overwrites for a target in the channel. The ``target`` parameter should either be a :class:`Member` or a :class:`Role` that belongs to guild. The ``overwrite`` parameter, if given, must either be ``None`` or :class:`PermissionOverwrite`. For convenience, you can pass in keyword arguments denoting :class:`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:`~Permissions.manage_roles` permission to use this. 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:`PermissionOverwrite` :: overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite) Parameters ----------- target The :class:`Member` or :class:`Role` to overwrite permissions for. overwrite: :class:`PermissionOverwrite` The permissions to allow and deny to the target. \*\*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 ------- Forbidden You do not have permissions to edit channel specific permissions. HTTPException Editing channel specific permissions failed. NotFound The role or member being edited is not part of the guild. InvalidArgument The overwrite parameter invalid or the target type was not :class:`Role` or :class:`Member`. 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:`Member` or a :class:`Role` that belongs to guild. The ``overwrite`` parameter, if given, must either be ``None`` or :class:`PermissionOverwrite`. For convenience, you can pass in keyword arguments denoting :class:`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:`~Permissions.manage_roles` permission to use this. 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:`PermissionOverwrite` :: overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite) Parameters ----------- target The :class:`Member` or :class:`Role` to overwrite permissions for. overwrite: :class:`PermissionOverwrite` The permissions to allow and deny to the target. \*\*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 ------- Forbidden You do not have permissions to edit channel specific permissions. HTTPException Editing channel specific permissions failed. NotFound The role or member being edited is not part of the guild. InvalidArgument The overwrite parameter invalid or the target type was not :class:`Role` or :class:`Member`. """ http = self._state.http if isinstance(target, User): perm_type = 'member' elif isinstance(target, Role): perm_type = 'role' else: raise InvalidArgument('target parameter must be either Member or Role') if isinstance(overwrite, _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.')
|coro| Creates an instant invite. You must have :attr:`~.Permissions.create_instant_invite` permission to do this. Parameters ------------ max_age: :class:`int` How long the invite should last. 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. Raises ------- HTTPException Invite creation failed. Returns -------- :class:`Invite` The invite that was created. async def create_invite(self, *, reason=None, **fields): """|coro| Creates an instant invite. You must have :attr:`~.Permissions.create_instant_invite` permission to do this. Parameters ------------ max_age: :class:`int` How long the invite should last. 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. Raises ------- HTTPException Invite creation failed. Returns -------- :class:`Invite` The invite that was created. """ data = await self._state.http.create_invite(self.id, reason=reason, **fields) return Invite.from_incomplete(data=data, state=self._state)
|coro| Returns a list of all active instant invites from this channel. You must have :attr:`~.Permissions.manage_guild` 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. async def invites(self): """|coro| Returns a list of all active instant invites from this channel. You must have :attr:`~.Permissions.manage_guild` 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. """ state = self._state data = await state.http.invites_from_channel(self.id) result = [] for invite in data: invite['channel'] = self invite['guild'] = self.guild result.append(Invite(state=state, data=invite)) return result
|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:`.File` object. To upload multiple files, the ``files`` parameter should be used with a :class:`list` of :class:`.File` objects. **Specifying both parameters will lead to an exception**. If the ``embed`` parameter is provided, it must be of type :class:`.Embed` and it must be a rich embed type. Parameters ------------ content The content of the message to send. tts: :class:`bool` Indicates if the message should be sent using text-to-speech. embed: :class:`.Embed` The rich embed for the content. file: :class:`.File` The file to upload. files: List[:class:`.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. Raises -------- :exc:`.HTTPException` Sending the message failed. :exc:`.Forbidden` You do not have the proper permissions to send the message. :exc:`.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. async def send(self, content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=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:`.File` object. To upload multiple files, the ``files`` parameter should be used with a :class:`list` of :class:`.File` objects. **Specifying both parameters will lead to an exception**. If the ``embed`` parameter is provided, it must be of type :class:`.Embed` and it must be a rich embed type. Parameters ------------ content The content of the message to send. tts: :class:`bool` Indicates if the message should be sent using text-to-speech. embed: :class:`.Embed` The rich embed for the content. file: :class:`.File` The file to upload. files: List[:class:`.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. Raises -------- :exc:`.HTTPException` Sending the message failed. :exc:`.Forbidden` You do not have the proper permissions to send the message. :exc:`.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. """ channel = await self._get_channel() state = self._state content = str(content) if content is not None else None if embed is not None: embed = embed.to_dict() 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], content=content, tts=tts, embed=embed, nonce=nonce) 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, nonce=nonce) finally: for f in files: f.close() else: data = await state.http.send_message(channel.id, content, tts=tts, embed=embed, nonce=nonce) ret = state.create_message(channel=channel, data=data) if delete_after is not None: await ret.delete(delay=delete_after) return ret
|coro| Triggers a *typing* indicator to the destination. *Typing* indicator will go away after 10 seconds, or after a message is sent. async def trigger_typing(self): """|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)
|coro| Retrieves a single :class:`.Message` from the destination. This can only be used by bot accounts. Parameters ------------ id: :class:`int` The message ID to look for. Raises -------- :exc:`.NotFound` The specified message was not found. :exc:`.Forbidden` You do not have the permissions required to get a message. :exc:`.HTTPException` Retrieving the message failed. Returns -------- :class:`.Message` The message asked for. async def fetch_message(self, id): """|coro| Retrieves a single :class:`.Message` from the destination. This can only be used by bot accounts. Parameters ------------ id: :class:`int` The message ID to look for. Raises -------- :exc:`.NotFound` The specified message was not found. :exc:`.Forbidden` You do not have the permissions required to get a message. :exc:`.HTTPException` Retrieving the message failed. Returns -------- :class:`.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)
|coro| Returns a :class:`list` of :class:`.Message` that are currently pinned. Raises ------- :exc:`.HTTPException` Retrieving the pinned messages failed. async def pins(self): """|coro| Returns a :class:`list` of :class:`.Message` that are currently pinned. Raises ------- :exc:`.HTTPException` Retrieving the pinned messages failed. """ 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]
Return an :class:`.AsyncIterator` that enables receiving the destination's message history. You must have :attr:`~.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: :class:`.Message` or :class:`datetime.datetime` Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. after: :class:`.Message` or :class:`datetime.datetime` Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. around: :class:`.Message` or :class:`datetime.datetime` Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC 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 ------ :exc:`.Forbidden` You do not have permissions to get channel message history. :exc:`.HTTPException` The request to get message history failed. Yields ------- :class:`.Message` The message with the message data parsed. def history(self, *, limit=100, before=None, after=None, around=None, oldest_first=None): """Return an :class:`.AsyncIterator` that enables receiving the destination's message history. You must have :attr:`~.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: :class:`.Message` or :class:`datetime.datetime` Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. after: :class:`.Message` or :class:`datetime.datetime` Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. around: :class:`.Message` or :class:`datetime.datetime` Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC 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 ------ :exc:`.Forbidden` You do not have permissions to get channel message history. :exc:`.HTTPException` The request to get message history failed. Yields ------- :class:`.Message` The message with the message data parsed. """ return HistoryIterator(self, limit=limit, before=before, after=after, around=around, oldest_first=oldest_first)
|coro| Connects to voice and creates a :class:`VoiceClient` to establish your connection to the voice server. 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. Raises ------- asyncio.TimeoutError Could not connect to the voice channel in time. ClientException You are already connected to a voice channel. OpusNotLoaded The opus library has not been loaded. Returns ------- :class:`VoiceClient` A voice client that is fully connected to the voice server. async def connect(self, *, timeout=60.0, reconnect=True): """|coro| Connects to voice and creates a :class:`VoiceClient` to establish your connection to the voice server. 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. Raises ------- asyncio.TimeoutError Could not connect to the voice channel in time. ClientException You are already connected to a voice channel. OpusNotLoaded The opus library has not been loaded. Returns ------- :class:`VoiceClient` 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.') voice = VoiceClient(state=state, timeout=timeout, channel=self) state._add_voice_client(key_id, voice) try: await voice.connect(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
:class:`Asset`:Returns an asset of the emoji, if it is custom. def url(self): """:class:`Asset`:Returns an asset of the emoji, if it is custom.""" if self.is_unicode_emoji(): return Asset(self._state) _format = 'gif' if self.animated else 'png' url = "https://cdn.discordapp.com/emojis/{0.id}.{1}".format(self, _format) return Asset(self._state, url)
List[:class:`Role`]: A :class:`list` of roles that is allowed to use this emoji. If roles is empty, the emoji is unrestricted. def roles(self): """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)]
|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. async def delete(self, *, reason=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)
r"""|coro| Edits the custom emoji. You must have :attr:`~Permissions.manage_emojis` permission to do this. Parameters ----------- name: :class:`str` The new emoji name. roles: Optional[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 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. async def edit(self, *, name, roles=None, reason=None): r"""|coro| Edits the custom emoji. You must have :attr:`~Permissions.manage_emojis` permission to do this. Parameters ----------- name: :class:`str` The new emoji name. roles: Optional[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 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. """ if roles: roles = [role.id for role in roles] await self._state.http.edit_custom_emoji(self.guild.id, self.id, name=name, roles=roles, reason=reason)
A decorator that schedules a task in the background for you with optional reconnect logic. 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. 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. Returns --------- :class:`Loop` The loop helper that handles the background task. def loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None): """A decorator that schedules a task in the background for you with optional reconnect logic. 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. 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. Returns --------- :class:`Loop` The loop helper that handles the background task. """ def decorator(func): return Loop(func, seconds=seconds, minutes=minutes, hours=hours, count=count, reconnect=reconnect, loop=loop) return decorator
r"""Starts the internal task in the event loop. Parameters ------------ \*args The arguments to to use. \*\*kwargs The keyword arguments to use. Raises -------- RuntimeError A task has already been launched. Returns --------- :class:`asyncio.Task` The task that has been created. def start(self, *args, **kwargs): r"""Starts the internal task in the event loop. Parameters ------------ \*args The arguments to to use. \*\*kwargs The keyword arguments to use. Raises -------- RuntimeError A task has already been launched. Returns --------- :class:`asyncio.Task` The task that has been created. """ if self._task is not None: raise RuntimeError('Task is already launched.') if self._injected is not None: args = (self._injected, *args) self._task = self.loop.create_task(self._loop(*args, **kwargs)) return self._task
r"""Adds an exception type 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 ------------ exc: Type[:class:`BaseException`] The exception class to handle. Raises -------- TypeError The exception passed is either not a class or not inherited from :class:`BaseException`. def add_exception_type(self, exc): r"""Adds an exception type 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 ------------ exc: Type[:class:`BaseException`] The exception class to handle. Raises -------- TypeError The exception passed is either not a class or not inherited from :class:`BaseException`. """ if not inspect.isclass(exc): raise TypeError('{0!r} must be a class.'.format(exc)) if not issubclass(exc, BaseException): raise TypeError('{0!r} must inherit from BaseException.'.format(exc)) self._valid_exception = (*self._valid_exception, exc)
Removes an exception type from being handled during the reconnect logic. Parameters ------------ exc: Type[:class:`BaseException`] The exception class to handle. Returns --------- :class:`bool` Whether it was successfully removed. def remove_exception_type(self, exc): """Removes an exception type from being handled during the reconnect logic. Parameters ------------ exc: Type[:class:`BaseException`] The exception class to handle. Returns --------- :class:`bool` Whether it was successfully removed. """ old_length = len(self._valid_exception) self._valid_exception = tuple(x for x in self._valid_exception if x is not exc) return len(self._valid_exception) != old_length
A function that also acts as a decorator to register 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`. Parameters ------------ coro: :term:`py:awaitable` The coroutine to register before the loop runs. Raises ------- TypeError The function was not a coroutine. def before_loop(self, coro): """A function that also acts as a decorator to register 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`. Parameters ------------ coro: :term:`py:awaitable` The coroutine to register before the loop runs. Raises ------- TypeError The function was not a coroutine. """ if not (inspect.iscoroutinefunction(coro) or inspect.isawaitable(coro)): raise TypeError('Expected coroutine or awaitable, received {0.__name__!r}.'.format(type(coro))) self._before_loop = coro
A function that also acts as a decorator to register a coroutine to be called after the loop finished running. Parameters ------------ coro: :term:`py:awaitable` The coroutine to register after the loop finishes. Raises ------- TypeError The function was not a coroutine. def after_loop(self, coro): """A function that also acts as a decorator to register a coroutine to be called after the loop finished running. Parameters ------------ coro: :term:`py:awaitable` The coroutine to register after the loop finishes. Raises ------- TypeError The function was not a coroutine. """ if not (inspect.iscoroutinefunction(coro) or inspect.isawaitable(coro)): raise TypeError('Expected coroutine or awaitable, received {0.__name__!r}.'.format(type(coro))) self._after_loop = coro
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 ------ You do not pass in the context as it is done for you. Warning --------- The first parameter passed **must** be the command being invoked. Parameters ----------- command: :class:`.Command` A command or subclass of a command that is going to be called. \*args The arguments to to use. \*\*kwargs The keyword arguments to use. async def invoke(self, *args, **kwargs): 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 ------ You do not pass in the context as it is done for you. Warning --------- The first parameter passed **must** be the command being invoked. Parameters ----------- command: :class:`.Command` A command or subclass of a command that is going to be called. \*args The arguments to to use. \*\*kwargs The keyword arguments to use. """ try: command = args[0] except IndexError: raise TypeError('Missing command to invoke.') from None arguments = [] if command.cog is not None: arguments.append(command.cog) arguments.append(self) arguments.extend(args[1:]) ret = await command.callback(*arguments, **kwargs) return ret
|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. async def reinvoke(self, *, call_hooks=False, restart=True): """|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. """ 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 subcommand_passed = self.subcommand_passed if restart: to_call = cmd.root_parent or cmd view.index = len(self.prefix) view.previous = 0 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.subcommand_passed = subcommand_passed
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts. def me(self): """Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.""" return self.guild.me if self.guild is not None else self.bot.user
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. async def send_help(self, *args): """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 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() return await cmd.send_bot_help(mapping) entity = args[0] if entity is None: return None if isinstance(entity, str): entity = bot.get_cog(entity) or bot.get_command(entity) try: qualified_name = 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) if hasattr(entity, '__cog_commands__'): return await cmd.send_cog_help(entity) elif isinstance(entity, Group): return await cmd.send_group_help(entity) elif isinstance(entity, Command): return await cmd.send_command_help(entity) else: return None
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. def delay(self): """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)
Returns True if self has the same or fewer permissions as other. def is_subset(self, other): """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("cannot compare {} with {}".format(self.__class__.__name__, other.__class__.__name__))
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. def update(self, **kwargs): 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(): try: is_property = isinstance(getattr(self.__class__, key), property) except AttributeError: continue if is_property: setattr(self, key, value)
:class:`AuditLogChanges`: The list of changes this entry has. def changes(self): """:class:`AuditLogChanges`: The list of changes this entry has.""" obj = AuditLogChanges(self, self._changes) del self._changes return obj
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. def command(name=None, cls=None, **attrs): """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 None: cls = Command def decorator(func): if isinstance(func, Command): raise TypeError('Callback is already a command.') return cls(func, name=name, **attrs) return decorator
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.0 The ``cls`` parameter can now be passed. def group(name=None, **attrs): """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.0 The ``cls`` parameter can now be passed. """ attrs.setdefault('cls', Group) return command(name=name, **attrs)
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`. .. note:: These functions can either be regular functions or coroutines. 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 check(predicate): 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`. .. note:: These functions can either be regular functions or coroutines. 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): 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 return decorator
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.0 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 has_role(item): """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.0 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): if not isinstance(ctx.channel, discord.abc.GuildChannel): raise NoPrivateMessage() if isinstance(item, int): role = discord.utils.get(ctx.author.roles, id=item) else: role = discord.utils.get(ctx.author.roles, name=item) if role is None: raise MissingRole(item) return True return check(predicate)
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.0 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 has_any_role(*items): 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.0 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 not isinstance(ctx.channel, discord.abc.GuildChannel): raise NoPrivateMessage() getter = functools.partial(discord.utils.get, ctx.author.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 MissingAnyRole(items) return check(predicate)
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.0 Raise :exc:`.BotMissingRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` def bot_has_role(item): """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.0 Raise :exc:`.BotMissingRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` """ def predicate(ctx): ch = ctx.channel if not isinstance(ch, discord.abc.GuildChannel): raise NoPrivateMessage() me = ch.guild.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)
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.0 Raise :exc:`.BotMissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic checkfailure def bot_has_any_role(*items): """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.0 Raise :exc:`.BotMissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic checkfailure """ def predicate(ctx): ch = ctx.channel if not isinstance(ch, discord.abc.GuildChannel): raise NoPrivateMessage() me = ch.guild.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(items) return check(predicate)
A :func:`.check` that is added that checks if the member has all of the permissions necessary. 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.') def has_permissions(**perms): """A :func:`.check` that is added that checks if the member has all of the permissions necessary. 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.') """ def predicate(ctx): ch = ctx.channel permissions = ch.permissions_for(ctx.author) missing = [perm for perm, value in perms.items() if getattr(permissions, perm, None) != value] if not missing: return True raise MissingPermissions(missing) return check(predicate)
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`. def bot_has_permissions(**perms): """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`. """ def predicate(ctx): guild = ctx.guild me = guild.me if guild is not None else ctx.bot.user permissions = ctx.channel.permissions_for(me) missing = [perm for perm, value in perms.items() if getattr(permissions, perm, None) != value] if not missing: return True raise BotMissingPermissions(missing) return check(predicate)
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`. def is_owner(): """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): if not await ctx.bot.is_owner(ctx.author): raise NotOwner('You do not own this bot.') return True return check(predicate)
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.0 Raise :exc:`.NSFWChannelRequired instead of generic :exc:`.CheckFailure`. DM channels will also now pass this check. def is_nsfw(): """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.0 Raise :exc:`.NSFWChannelRequired instead of generic :exc:`.CheckFailure`. DM channels will also now pass this check. """ def pred(ctx): ch = ctx.channel if ctx.guild is None or (isinstance(ch, discord.TextChannel) and ch.is_nsfw()): return True raise NSFWChannelRequired(ch) return check(pred)
A decorator that adds a cooldown to a :class:`.Command` or its subclasses. 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, or global basis. Denoted by the third argument of ``type`` which must be of enum type ``BucketType`` which could be either: - ``BucketType.default`` for a global basis. - ``BucketType.user`` for a per-user basis. - ``BucketType.guild`` for a per-guild basis. - ``BucketType.channel`` for a per-channel basis. - ``BucketType.member`` for a per-member basis. - ``BucketType.category`` for a per-category basis. 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: ``BucketType`` The type of cooldown to have. def cooldown(rate, per, type=BucketType.default): """A decorator that adds a cooldown to a :class:`.Command` or its subclasses. 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, or global basis. Denoted by the third argument of ``type`` which must be of enum type ``BucketType`` which could be either: - ``BucketType.default`` for a global basis. - ``BucketType.user`` for a per-user basis. - ``BucketType.guild`` for a per-guild basis. - ``BucketType.channel`` for a per-channel basis. - ``BucketType.member`` for a per-member basis. - ``BucketType.category`` for a per-category basis. 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: ``BucketType`` The type of cooldown to have. """ def decorator(func): if isinstance(func, Command): func._buckets = CooldownMapping(Cooldown(rate, per, type)) else: func.__commands_cooldown__ = Cooldown(rate, per, type) return func return decorator
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. def update(self, **kwargs): """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))
Creates a copy of this :class:`Command`. def copy(self): """Creates a copy of this :class:`Command`.""" ret = self.__class__(self.callback, **self.__original_kwargs__) return self._ensure_assignment_on_copy(ret)
Retrieves the parameter OrderedDict without the context or self parameters. Useful for inspecting signature. def clean_params(self): """Retrieves the parameter OrderedDict without the context or self parameters. Useful for inspecting signature. """ result = self.params.copy() if self.cog is not None: # first parameter is self result.popitem(last=False) try: # first/second parameter is context result.popitem(last=False) except Exception: raise ValueError('Missing context parameter') from None return result
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``. def full_parent_name(self): """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 while command.parent is not None: command = command.parent entries.append(command.name) return ' '.join(reversed(entries))
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.0 def parents(self): """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.0 """ entries = [] command = self while command.parent is not None: command = command.parent entries.append(command) return entries
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``. def qualified_name(self): """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
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. def is_on_cooldown(self, ctx): """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) return bucket.get_tokens() == 0
Resets the cooldown on this command. Parameters ----------- ctx: :class:`.Context` The invocation context to reset the cooldown under. def reset_cooldown(self, ctx): """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()
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. def error(self, coro): """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 = coro return coro
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. def before_invoke(self, coro): """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
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. def after_invoke(self, coro): """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
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. def short_doc(self): """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 ''
Returns a POSIX-like signature useful for help command output. def signature(self): """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, converters._Greedy) 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('[%s=%s]' % (name, param.default) if not greedy else '[%s=%s]...' % (name, param.default)) continue else: result.append('[%s]' % name) elif param.kind == param.VAR_POSITIONAL: result.append('[%s...]' % name) elif greedy: result.append('[%s]...' % name) elif self._is_typing_optional(param.annotation): result.append('[%s]' % name) else: result.append('<%s>' % name) return ' '.join(result)
|coro| Checks if the command can be executed by checking all the predicates inside the :attr:`.checks` attribute. 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. async def can_run(self, ctx): """|coro| Checks if the command can be executed by checking all the predicates inside the :attr:`.checks` attribute. 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. """ original = ctx.command ctx.command = self try: if not await ctx.bot.can_run(ctx): raise CheckFailure('The global check functions for command {0.qualified_name} failed.'.format(self)) 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) finally: ctx.command = original
Adds a :class:`.Command` or its subclasses 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. Parameters ----------- command The command to add. Raises ------- :exc:`.ClientException` If the command is already registered. TypeError If the command passed is not a subclass of :class:`.Command`. def add_command(self, command): """Adds a :class:`.Command` or its subclasses 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. Parameters ----------- command The command to add. Raises ------- :exc:`.ClientException` If the command is already registered. 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 discord.ClientException('Command {0.name} is already registered.'.format(command)) self.all_commands[command.name] = command for alias in command.aliases: if alias in self.all_commands: raise discord.ClientException('The alias {} is already an existing command or alias.'.format(alias)) self.all_commands[alias] = command
Remove a :class:`.Command` or subclasses 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 -------- :class:`.Command` or subclass The command that was removed. If the name is not valid then `None` is returned instead. def remove_command(self, name): """Remove a :class:`.Command` or subclasses 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 -------- :class:`.Command` or subclass 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: self.all_commands.pop(alias, None) return command
An iterator that recursively walks through all commands and subcommands. def walk_commands(self): """An iterator that recursively walks through all commands and subcommands.""" for command in tuple(self.all_commands.values()): yield command if isinstance(command, GroupMixin): yield from command.walk_commands()
Get a :class:`.Command` or subclasses 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 -------- :class:`Command` or subclass The command that was requested. If not found, returns ``None``. def get_command(self, name): """Get a :class:`.Command` or subclasses 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 -------- :class:`Command` or subclass 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() 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] except (AttributeError, KeyError): return None return obj
A shortcut decorator that invokes :func:`.command` and adds it to the internal command list via :meth:`~.GroupMixin.add_command`. def command(self, *args, **kwargs): """A shortcut decorator that invokes :func:`.command` and adds it to the internal command list via :meth:`~.GroupMixin.add_command`. """ def decorator(func): kwargs.setdefault('parent', self) result = command(*args, **kwargs)(func) self.add_command(result) return result return decorator
Creates a copy of this :class:`Group`. def copy(self): """Creates a copy of this :class:`Group`.""" ret = super().copy() for cmd in self.commands: ret.add_command(cmd.copy()) return ret
|coro| Retrieves the content of this asset as a :class:`bytes` object. .. warning:: :class:`PartialEmoji` won't have a connection state if user created, and a URL won't be present if a custom image isn't associated with the asset, e.g. a guild with no custom icon. .. versionadded:: 1.1.0 Raises ------ DiscordException There was no valid URL or internal connection state. HTTPException Downloading the asset failed. NotFound The asset was deleted. Returns ------- :class:`bytes` The content of the asset. async def read(self): """|coro| Retrieves the content of this asset as a :class:`bytes` object. .. warning:: :class:`PartialEmoji` won't have a connection state if user created, and a URL won't be present if a custom image isn't associated with the asset, e.g. a guild with no custom icon. .. versionadded:: 1.1.0 Raises ------ DiscordException There was no valid URL or internal connection state. HTTPException Downloading the asset failed. NotFound The asset was deleted. Returns ------- :class:`bytes` The content of the asset. """ if not self._url: raise DiscordException('Invalid asset (no URL provided)') if self._state is None: raise DiscordException('Invalid state (no ConnectionState provided)') return await self._state.http.get_from_cdn(self._url)
|coro| Saves this asset into a file-like object. Parameters ---------- fp: Union[BinaryIO, :class:`os.PathLike`] Same as in :meth:`Attachment.save`. seek_begin: :class:`bool` Same as in :meth:`Attachment.save`. Raises ------ Same as :meth:`read`. Returns -------- :class:`int` The number of bytes written. async def save(self, fp, *, seek_begin=True): """|coro| Saves this asset into a file-like object. Parameters ---------- fp: Union[BinaryIO, :class:`os.PathLike`] Same as in :meth:`Attachment.save`. seek_begin: :class:`bool` Same as in :meth:`Attachment.save`. Raises ------ Same as :meth:`read`. Returns -------- :class:`int` The number of bytes written. """ data = await self.read() if isinstance(fp, io.IOBase) and fp.writable(): written = fp.write(data) if seek_begin: fp.seek(0) return written else: with open(fp, 'wb') as f: return f.write(data)
Creates a main websocket for Discord from a :class:`Client`. This is for internal use only. async def from_client(cls, client, *, 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 = await client.http.get_gateway() ws = await websockets.connect(gateway, loop=client.loop, klass=cls, compression=None) # dynamically add attributes needed ws.token = client.http.token ws._connection = client._connection ws._dispatch = client.dispatch ws.gateway = gateway ws.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 client._connection._update_references(ws) log.info('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() try: await ws.ensure_open() except websockets.exceptions.ConnectionClosed: # ws got closed so let's just do a regular IDENTIFY connect. log.info('RESUME failed (the websocket decided to close) for Shard ID %s. Retrying.', shard_id) return await cls.from_client(client, shard_id=shard_id) else: return ws
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. 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
Sends the IDENTIFY packet. 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 not self._connection.is_bot: payload['d']['synced_guilds'] = [] 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 } await self.send_as_json(payload) log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)
Sends the RESUME packet. 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)
Polls for a DISPATCH event and handles the general gateway loop. Raises ------ ConnectionClosed The websocket connection was terminated for unhandled reasons. 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.recv() await self.received_message(msg) except websockets.exceptions.ConnectionClosed as exc: if self._can_handle_close(exc.code): log.info('Websocket closed with %s (%s), attempting a reconnect.', exc.code, exc.reason) raise ResumeWebSocket(self.shard_id) from exc else: log.info('Websocket closed with %s (%s), cannot reconnect.', exc.code, exc.reason) raise ConnectionClosed(exc, shard_id=self.shard_id) from exc
Creates a voice websocket for the :class:`VoiceClient`. async def from_client(cls, client, *, resume=False): """Creates a voice websocket for the :class:`VoiceClient`.""" gateway = 'wss://' + client.endpoint + '/?v=4' ws = await websockets.connect(gateway, loop=client.loop, klass=cls, compression=None) ws.gateway = gateway ws._connection = client ws._max_heartbeat_timeout = 60.0 if resume: await ws.resume() else: await ws.identify() return ws
Clears the paginator to have no pages. 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) + 1 # prefix + newline else: self._current_page = [] self._count = 0 self._pages = []
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`. 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 - 2 if len(line) > max_page_size: raise RuntimeError('Line exceeds maximum page size %s' % (max_page_size)) if self._count + len(line) + 1 > self.max_size: self.close_page() self._count += len(line) + 1 self._current_page.append(line) if empty: self._current_page.append('') self._count += 1
Prematurely terminate a page. def close_page(self): """Prematurely terminate a page.""" if self.suffix is not None: self._current_page.append(self.suffix) self._pages.append('\n'.join(self._current_page)) if self.prefix is not None: self._current_page = [self.prefix] self._count = len(self.prefix) + 1 # prefix + newline else: self._current_page = [] self._count = 0
Retrieves the bot mapping passed to :meth:`send_bot_help`. 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.all_commands.values() if c.cog is None] return mapping
The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``. def clean_prefix(self): """The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.""" user = self.context.guild.me if self.context.guild else self.context.bot.user # 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. return self.context.prefix.replace(user.mention, '@' + user.display_name)
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. 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
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. 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.full_parent_name if len(command.aliases) > 0: aliases = '|'.join(command.aliases) fmt = '[%s|%s]' % (command.name, aliases) if parent: fmt = parent + ' ' + fmt alias = fmt else: alias = command.name if not parent else parent + ' ' + command.name return '%s%s %s' % (self.clean_prefix, alias, command.signature)
Removes mentions from the string to prevent abuse. This includes ``@everyone``, ``@here``, member mentions and role mentions. def remove_mentions(self, string): """Removes mentions from the string to prevent abuse. This includes ``@everyone``, ``@here``, member mentions and role mentions. """ def replace(obj, *, transforms=self.MENTION_TRANSFORMS): return transforms.get(obj.group(0), '@invalid') return self.MENTION_PATTERN.sub(replace, 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. 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 'Command "{0.qualified_name}" has no subcommand named {1}'.format(command, string) return 'Command "{0.qualified_name}" has no subcommands.'.format(command)
|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. 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 not self.verify_checks: # 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 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
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. 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)
|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` 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)
Shortens text to fit into the :attr:`width`. def shorten_text(self, text): """Shortens text to fit into the :attr:`width`.""" if len(text) > self.width: return text[:self.width - 3] + '...' return text
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:`get_max_size` on the commands parameter. 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:`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 = '{0}{1:<{width}} {2}'.format(self.indent * ' ', name, command.short_doc, width=width) self.paginator.add_line(self.shorten_text(entry))