repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Rapptz/discord.py
|
discord/channel.py
|
TextChannel.webhooks
|
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]
|
python
|
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]
|
[
"async",
"def",
"webhooks",
"(",
"self",
")",
":",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"channel_webhooks",
"(",
"self",
".",
"id",
")",
"return",
"[",
"Webhook",
".",
"from_state",
"(",
"d",
",",
"state",
"=",
"self",
".",
"_state",
")",
"for",
"d",
"in",
"data",
"]"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L385-L404
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
TextChannel.create_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)
|
python
|
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)
|
[
"async",
"def",
"create_webhook",
"(",
"self",
",",
"*",
",",
"name",
",",
"avatar",
"=",
"None",
",",
"reason",
"=",
"None",
")",
":",
"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",
")"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L406-L443
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
VoiceChannel.members
|
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
|
python
|
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
|
[
"def",
"members",
"(",
"self",
")",
":",
"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"
] |
Returns a list of :class:`Member` that are currently inside this voice channel.
|
[
"Returns",
"a",
"list",
"of",
":",
"class",
":",
"Member",
"that",
"are",
"currently",
"inside",
"this",
"voice",
"channel",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L520-L528
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
CategoryChannel.edit
|
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)
|
python
|
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)
|
[
"async",
"def",
"edit",
"(",
"self",
",",
"*",
",",
"reason",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"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",
")"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L661-L700
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
CategoryChannel.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
|
python
|
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
|
[
"def",
"channels",
"(",
"self",
")",
":",
"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:`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.
|
[
"List",
"[",
":",
"class",
":",
"abc",
".",
"GuildChannel",
"]",
":",
"Returns",
"the",
"channels",
"that",
"are",
"under",
"this",
"category",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L703-L713
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
CategoryChannel.text_channels
|
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
|
python
|
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
|
[
"def",
"text_channels",
"(",
"self",
")",
":",
"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:`TextChannel`]: Returns the text channels that are under this category.
|
[
"List",
"[",
":",
"class",
":",
"TextChannel",
"]",
":",
"Returns",
"the",
"text",
"channels",
"that",
"are",
"under",
"this",
"category",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L716-L722
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
CategoryChannel.voice_channels
|
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
|
python
|
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
|
[
"def",
"voice_channels",
"(",
"self",
")",
":",
"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"
] |
List[:class:`VoiceChannel`]: Returns the voice channels that are under this category.
|
[
"List",
"[",
":",
"class",
":",
"VoiceChannel",
"]",
":",
"Returns",
"the",
"voice",
"channels",
"that",
"are",
"under",
"this",
"category",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L725-L731
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
CategoryChannel.create_text_channel
|
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)
|
python
|
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)
|
[
"async",
"def",
"create_text_channel",
"(",
"self",
",",
"name",
",",
"*",
",",
"overwrites",
"=",
"None",
",",
"reason",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"return",
"await",
"self",
".",
"guild",
".",
"create_text_channel",
"(",
"name",
",",
"overwrites",
"=",
"overwrites",
",",
"category",
"=",
"self",
",",
"reason",
"=",
"reason",
",",
"*",
"*",
"options",
")"
] |
|coro|
A shortcut method to :meth:`Guild.create_text_channel` to create a :class:`TextChannel` in the category.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L733-L738
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
CategoryChannel.create_voice_channel
|
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)
|
python
|
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)
|
[
"async",
"def",
"create_voice_channel",
"(",
"self",
",",
"name",
",",
"*",
",",
"overwrites",
"=",
"None",
",",
"reason",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"return",
"await",
"self",
".",
"guild",
".",
"create_voice_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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L740-L745
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
DMChannel.permissions_for
|
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
|
python
|
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
|
[
"def",
"permissions_for",
"(",
"self",
",",
"user",
"=",
"None",
")",
":",
"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.
Parameters
-----------
user: :class:`User`
The user to check permissions for. This parameter is ignored
but kept for compatibility.
Returns
--------
:class:`Permissions`
The resolved permissions.
|
[
"Handles",
"permission",
"resolution",
"for",
"a",
":",
"class",
":",
"User",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L923-L950
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
GroupChannel.permissions_for
|
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
|
python
|
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
|
[
"def",
"permissions_for",
"(",
"self",
",",
"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"
] |
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.
|
[
"Handles",
"permission",
"resolution",
"for",
"a",
":",
"class",
":",
"User",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L1041-L1074
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
GroupChannel.add_recipients
|
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)
|
python
|
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)
|
[
"async",
"def",
"add_recipients",
"(",
"self",
",",
"*",
"recipients",
")",
":",
"# 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|
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.
|
[
"r",
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L1076-L1101
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
GroupChannel.remove_recipients
|
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)
|
python
|
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)
|
[
"async",
"def",
"remove_recipients",
"(",
"self",
",",
"*",
"recipients",
")",
":",
"# TODO: wait for the corresponding WS event",
"req",
"=",
"self",
".",
"_state",
".",
"http",
".",
"remove_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.
|
[
"r",
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L1103-L1123
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
GroupChannel.edit
|
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)
|
python
|
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)
|
[
"async",
"def",
"edit",
"(",
"self",
",",
"*",
"*",
"fields",
")",
":",
"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",
")"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L1125-L1154
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
GuildChannel.changed_roles
|
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
|
python
|
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
|
[
"def",
"changed_roles",
"(",
"self",
")",
":",
"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 a :class:`list` of :class:`Roles` that have been overridden from
their default values in the :attr:`Guild.roles` attribute.
|
[
"Returns",
"a",
":",
"class",
":",
"list",
"of",
":",
"class",
":",
"Roles",
"that",
"have",
"been",
"overridden",
"from",
"their",
"default",
"values",
"in",
"the",
":",
"attr",
":",
"Guild",
".",
"roles",
"attribute",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L290-L303
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
GuildChannel.overwrites_for
|
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()
|
python
|
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()
|
[
"def",
"overwrites_for",
"(",
"self",
",",
"obj",
")",
":",
"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 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.
|
[
"Returns",
"the",
"channel",
"-",
"specific",
"overwrites",
"for",
"a",
"member",
"or",
"a",
"role",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L315-L343
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
GuildChannel.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
|
python
|
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
|
[
"def",
"overwrites",
"(",
"self",
")",
":",
"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"
] |
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.
|
[
"Returns",
"all",
"of",
"the",
"channel",
"s",
"overwrites",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L346-L376
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
GuildChannel.permissions_for
|
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
|
python
|
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
|
[
"def",
"permissions_for",
"(",
"self",
",",
"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"
] |
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.
|
[
"Handles",
"permission",
"resolution",
"for",
"the",
"current",
":",
"class",
":",
"Member",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L386-L486
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
GuildChannel.delete
|
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)
|
python
|
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)
|
[
"async",
"def",
"delete",
"(",
"self",
",",
"*",
",",
"reason",
"=",
"None",
")",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"delete_channel",
"(",
"self",
".",
"id",
",",
"reason",
"=",
"reason",
")"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L488-L510
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
GuildChannel.set_permissions
|
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.')
|
python
|
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.')
|
[
"async",
"def",
"set_permissions",
"(",
"self",
",",
"target",
",",
"*",
",",
"overwrite",
"=",
"_undefined",
",",
"reason",
"=",
"None",
",",
"*",
"*",
"permissions",
")",
":",
"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.'",
")"
] |
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`.
|
[
"r",
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L512-L604
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
GuildChannel.create_invite
|
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)
|
python
|
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)
|
[
"async",
"def",
"create_invite",
"(",
"self",
",",
"*",
",",
"reason",
"=",
"None",
",",
"*",
"*",
"fields",
")",
":",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"create_invite",
"(",
"self",
".",
"id",
",",
"reason",
"=",
"reason",
",",
"*",
"*",
"fields",
")",
"return",
"Invite",
".",
"from_incomplete",
"(",
"data",
"=",
"data",
",",
"state",
"=",
"self",
".",
"_state",
")"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L646-L684
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
GuildChannel.invites
|
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
|
python
|
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
|
[
"async",
"def",
"invites",
"(",
"self",
")",
":",
"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|
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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L686-L715
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
Messageable.send
|
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
|
python
|
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
|
[
"async",
"def",
"send",
"(",
"self",
",",
"content",
"=",
"None",
",",
"*",
",",
"tts",
"=",
"False",
",",
"embed",
"=",
"None",
",",
"file",
"=",
"None",
",",
"files",
"=",
"None",
",",
"delete_after",
"=",
"None",
",",
"nonce",
"=",
"None",
")",
":",
"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|
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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L738-L828
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
Messageable.trigger_typing
|
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)
|
python
|
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)
|
[
"async",
"def",
"trigger_typing",
"(",
"self",
")",
":",
"channel",
"=",
"await",
"self",
".",
"_get_channel",
"(",
")",
"await",
"self",
".",
"_state",
".",
"http",
".",
"send_typing",
"(",
"channel",
".",
"id",
")"
] |
|coro|
Triggers a *typing* indicator to the destination.
*Typing* indicator will go away after 10 seconds, or after a message is sent.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L830-L839
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
Messageable.fetch_message
|
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)
|
python
|
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)
|
[
"async",
"def",
"fetch_message",
"(",
"self",
",",
"id",
")",
":",
"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|
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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L860-L889
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
Messageable.pins
|
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]
|
python
|
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]
|
[
"async",
"def",
"pins",
"(",
"self",
")",
":",
"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",
"]"
] |
|coro|
Returns a :class:`list` of :class:`.Message` that are currently pinned.
Raises
-------
:exc:`.HTTPException`
Retrieving the pinned messages failed.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L891-L905
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
Messageable.history
|
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)
|
python
|
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)
|
[
"def",
"history",
"(",
"self",
",",
"*",
",",
"limit",
"=",
"100",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
",",
"around",
"=",
"None",
",",
"oldest_first",
"=",
"None",
")",
":",
"return",
"HistoryIterator",
"(",
"self",
",",
"limit",
"=",
"limit",
",",
"before",
"=",
"before",
",",
"after",
"=",
"after",
",",
"around",
"=",
"around",
",",
"oldest_first",
"=",
"oldest_first",
")"
] |
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",
"an",
":",
"class",
":",
".",
"AsyncIterator",
"that",
"enables",
"receiving",
"the",
"destination",
"s",
"message",
"history",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L907-L962
|
train
|
Rapptz/discord.py
|
discord/abc.py
|
Connectable.connect
|
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
|
python
|
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
|
[
"async",
"def",
"connect",
"(",
"self",
",",
"*",
",",
"timeout",
"=",
"60.0",
",",
"reconnect",
"=",
"True",
")",
":",
"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"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L983-L1031
|
train
|
Rapptz/discord.py
|
discord/emoji.py
|
PartialEmoji.url
|
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)
|
python
|
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)
|
[
"def",
"url",
"(",
"self",
")",
":",
"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",
")"
] |
:class:`Asset`:Returns an asset of the emoji, if it is custom.
|
[
":",
"class",
":",
"Asset",
":",
"Returns",
"an",
"asset",
"of",
"the",
"emoji",
"if",
"it",
"is",
"custom",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/emoji.py#L116-L123
|
train
|
Rapptz/discord.py
|
discord/emoji.py
|
Emoji.roles
|
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)]
|
python
|
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)]
|
[
"def",
"roles",
"(",
"self",
")",
":",
"guild",
"=",
"self",
".",
"guild",
"if",
"guild",
"is",
"None",
":",
"return",
"[",
"]",
"return",
"[",
"role",
"for",
"role",
"in",
"guild",
".",
"roles",
"if",
"self",
".",
"_roles",
".",
"has",
"(",
"role",
".",
"id",
")",
"]"
] |
List[:class:`Role`]: A :class:`list` of roles that is allowed to use this emoji.
If roles is empty, the emoji is unrestricted.
|
[
"List",
"[",
":",
"class",
":",
"Role",
"]",
":",
"A",
":",
"class",
":",
"list",
"of",
"roles",
"that",
"is",
"allowed",
"to",
"use",
"this",
"emoji",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/emoji.py#L229-L238
|
train
|
Rapptz/discord.py
|
discord/emoji.py
|
Emoji.delete
|
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)
|
python
|
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)
|
[
"async",
"def",
"delete",
"(",
"self",
",",
"*",
",",
"reason",
"=",
"None",
")",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"delete_custom_emoji",
"(",
"self",
".",
"guild",
".",
"id",
",",
"self",
".",
"id",
",",
"reason",
"=",
"reason",
")"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/emoji.py#L245-L266
|
train
|
Rapptz/discord.py
|
discord/emoji.py
|
Emoji.edit
|
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)
|
python
|
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)
|
[
"async",
"def",
"edit",
"(",
"self",
",",
"*",
",",
"name",
",",
"roles",
"=",
"None",
",",
"reason",
"=",
"None",
")",
":",
"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",
")"
] |
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.
|
[
"r",
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/emoji.py#L268-L295
|
train
|
Rapptz/discord.py
|
discord/ext/tasks/__init__.py
|
loop
|
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
|
python
|
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
|
[
"def",
"loop",
"(",
"*",
",",
"seconds",
"=",
"0",
",",
"minutes",
"=",
"0",
",",
"hours",
"=",
"0",
",",
"count",
"=",
"None",
",",
"reconnect",
"=",
"True",
",",
"loop",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"return",
"Loop",
"(",
"func",
",",
"seconds",
"=",
"seconds",
",",
"minutes",
"=",
"minutes",
",",
"hours",
"=",
"hours",
",",
"count",
"=",
"count",
",",
"reconnect",
"=",
"reconnect",
",",
"loop",
"=",
"loop",
")",
"return",
"decorator"
] |
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.
|
[
"A",
"decorator",
"that",
"schedules",
"a",
"task",
"in",
"the",
"background",
"for",
"you",
"with",
"optional",
"reconnect",
"logic",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L238-L276
|
train
|
Rapptz/discord.py
|
discord/ext/tasks/__init__.py
|
Loop.start
|
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
|
python
|
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
|
[
"def",
"start",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"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"""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.
|
[
"r",
"Starts",
"the",
"internal",
"task",
"in",
"the",
"event",
"loop",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L101-L129
|
train
|
Rapptz/discord.py
|
discord/ext/tasks/__init__.py
|
Loop.add_exception_type
|
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)
|
python
|
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)
|
[
"def",
"add_exception_type",
"(",
"self",
",",
"exc",
")",
":",
"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",
")"
] |
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`.
|
[
"r",
"Adds",
"an",
"exception",
"type",
"to",
"be",
"handled",
"during",
"the",
"reconnect",
"logic",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L137-L163
|
train
|
Rapptz/discord.py
|
discord/ext/tasks/__init__.py
|
Loop.remove_exception_type
|
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
|
python
|
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
|
[
"def",
"remove_exception_type",
"(",
"self",
",",
"exc",
")",
":",
"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"
] |
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.
|
[
"Removes",
"an",
"exception",
"type",
"from",
"being",
"handled",
"during",
"the",
"reconnect",
"logic",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L174-L189
|
train
|
Rapptz/discord.py
|
discord/ext/tasks/__init__.py
|
Loop.before_loop
|
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
|
python
|
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
|
[
"def",
"before_loop",
"(",
"self",
",",
"coro",
")",
":",
"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 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.
|
[
"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",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L195-L215
|
train
|
Rapptz/discord.py
|
discord/ext/tasks/__init__.py
|
Loop.after_loop
|
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
|
python
|
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
|
[
"def",
"after_loop",
"(",
"self",
",",
"coro",
")",
":",
"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"
] |
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.
|
[
"A",
"function",
"that",
"also",
"acts",
"as",
"a",
"decorator",
"to",
"register",
"a",
"coroutine",
"to",
"be",
"called",
"after",
"the",
"loop",
"finished",
"running",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L218-L236
|
train
|
Rapptz/discord.py
|
discord/ext/commands/context.py
|
Context.invoke
|
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
|
python
|
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
|
[
"async",
"def",
"invoke",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"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"
] |
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.
|
[
"r",
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/context.py#L89-L128
|
train
|
Rapptz/discord.py
|
discord/ext/commands/context.py
|
Context.reinvoke
|
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
|
python
|
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
|
[
"async",
"def",
"reinvoke",
"(",
"self",
",",
"*",
",",
"call_hooks",
"=",
"False",
",",
"restart",
"=",
"True",
")",
":",
"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"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/context.py#L130-L182
|
train
|
Rapptz/discord.py
|
discord/ext/commands/context.py
|
Context.me
|
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
|
python
|
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
|
[
"def",
"me",
"(",
"self",
")",
":",
"return",
"self",
".",
"guild",
".",
"me",
"if",
"self",
".",
"guild",
"is",
"not",
"None",
"else",
"self",
".",
"bot",
".",
"user"
] |
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.
|
[
"Similar",
"to",
":",
"attr",
":",
".",
"Guild",
".",
"me",
"except",
"it",
"may",
"return",
"the",
":",
"class",
":",
".",
"ClientUser",
"in",
"private",
"message",
"contexts",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/context.py#L216-L218
|
train
|
Rapptz/discord.py
|
discord/ext/commands/context.py
|
Context.send_help
|
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
|
python
|
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
|
[
"async",
"def",
"send_help",
"(",
"self",
",",
"*",
"args",
")",
":",
"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"
] |
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.
|
[
"send_help",
"(",
"entity",
"=",
"<bot",
">",
")"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/context.py#L226-L293
|
train
|
Rapptz/discord.py
|
discord/backoff.py
|
ExponentialBackoff.delay
|
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)
|
python
|
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)
|
[
"def",
"delay",
"(",
"self",
")",
":",
"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",
")"
] |
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.
|
[
"Compute",
"the",
"next",
"delay"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/backoff.py#L66-L85
|
train
|
Rapptz/discord.py
|
discord/permissions.py
|
Permissions.is_subset
|
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__))
|
python
|
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__))
|
[
"def",
"is_subset",
"(",
"self",
",",
"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__",
")",
")"
] |
Returns True if self has the same or fewer permissions as other.
|
[
"Returns",
"True",
"if",
"self",
"has",
"the",
"same",
"or",
"fewer",
"permissions",
"as",
"other",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/permissions.py#L99-L104
|
train
|
Rapptz/discord.py
|
discord/permissions.py
|
Permissions.update
|
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)
|
python
|
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)
|
[
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"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",
")"
] |
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.
|
[
"r",
"Bulk",
"updates",
"this",
"permission",
"object",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/permissions.py#L171-L190
|
train
|
Rapptz/discord.py
|
discord/audit_logs.py
|
AuditLogEntry.changes
|
def changes(self):
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj
|
python
|
def changes(self):
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
del self._changes
return obj
|
[
"def",
"changes",
"(",
"self",
")",
":",
"obj",
"=",
"AuditLogChanges",
"(",
"self",
",",
"self",
".",
"_changes",
")",
"del",
"self",
".",
"_changes",
"return",
"obj"
] |
:class:`AuditLogChanges`: The list of changes this entry has.
|
[
":",
"class",
":",
"AuditLogChanges",
":",
"The",
"list",
"of",
"changes",
"this",
"entry",
"has",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/audit_logs.py#L286-L290
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
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
|
python
|
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
|
[
"def",
"command",
"(",
"name",
"=",
"None",
",",
"cls",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"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:`.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.
|
[
"A",
"decorator",
"that",
"transforms",
"a",
"function",
"into",
"a",
":",
"class",
":",
".",
"Command",
"or",
"if",
"called",
"with",
":",
"func",
":",
".",
"group",
":",
"class",
":",
".",
"Group",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1200-L1238
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
group
|
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)
|
python
|
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)
|
[
"def",
"group",
"(",
"name",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"attrs",
".",
"setdefault",
"(",
"'cls'",
",",
"Group",
")",
"return",
"command",
"(",
"name",
"=",
"name",
",",
"*",
"*",
"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.
|
[
"A",
"decorator",
"that",
"transforms",
"a",
"function",
"into",
"a",
":",
"class",
":",
".",
"Group",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1240-L1251
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
check
|
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
|
python
|
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
|
[
"def",
"check",
"(",
"predicate",
")",
":",
"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"
] |
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.
|
[
"r",
"A",
"decorator",
"that",
"adds",
"a",
"check",
"to",
"the",
":",
"class",
":",
".",
"Command",
"or",
"its",
"subclasses",
".",
"These",
"checks",
"could",
"be",
"accessed",
"via",
":",
"attr",
":",
".",
"Command",
".",
"checks",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1253-L1316
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
has_role
|
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)
|
python
|
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)
|
[
"def",
"has_role",
"(",
"item",
")",
":",
"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",
")"
] |
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.
|
[
"A",
":",
"func",
":",
".",
"check",
"that",
"is",
"added",
"that",
"checks",
"if",
"the",
"member",
"invoking",
"the",
"command",
"has",
"the",
"role",
"specified",
"via",
"the",
"name",
"or",
"ID",
"specified",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1318-L1357
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
has_any_role
|
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)
|
python
|
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)
|
[
"def",
"has_any_role",
"(",
"*",
"items",
")",
":",
"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",
")"
] |
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')
|
[
"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",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1359-L1399
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
bot_has_role
|
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)
|
python
|
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)
|
[
"def",
"bot_has_role",
"(",
"item",
")",
":",
"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_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`
|
[
"Similar",
"to",
":",
"func",
":",
".",
"has_role",
"except",
"checks",
"if",
"the",
"bot",
"itself",
"has",
"the",
"role",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1401-L1428
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
bot_has_any_role
|
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)
|
python
|
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)
|
[
"def",
"bot_has_any_role",
"(",
"*",
"items",
")",
":",
"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",
")"
] |
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
|
[
"Similar",
"to",
":",
"func",
":",
".",
"has_any_role",
"except",
"checks",
"if",
"the",
"bot",
"itself",
"has",
"any",
"of",
"the",
"roles",
"listed",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1430-L1453
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
has_permissions
|
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)
|
python
|
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)
|
[
"def",
"has_permissions",
"(",
"*",
"*",
"perms",
")",
":",
"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",
")"
] |
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.')
|
[
"A",
":",
"func",
":",
".",
"check",
"that",
"is",
"added",
"that",
"checks",
"if",
"the",
"member",
"has",
"all",
"of",
"the",
"permissions",
"necessary",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1455-L1492
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
bot_has_permissions
|
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)
|
python
|
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)
|
[
"def",
"bot_has_permissions",
"(",
"*",
"*",
"perms",
")",
":",
"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",
")"
] |
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`.
|
[
"Similar",
"to",
":",
"func",
":",
".",
"has_permissions",
"except",
"checks",
"if",
"the",
"bot",
"itself",
"has",
"the",
"permissions",
"listed",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1494-L1513
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
is_owner
|
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)
|
python
|
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)
|
[
"def",
"is_owner",
"(",
")",
":",
"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 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`.
|
[
"A",
":",
"func",
":",
".",
"check",
"that",
"checks",
"if",
"the",
"person",
"invoking",
"this",
"command",
"is",
"the",
"owner",
"of",
"the",
"bot",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1549-L1564
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
is_nsfw
|
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)
|
python
|
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)
|
[
"def",
"is_nsfw",
"(",
")",
":",
"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 :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.
|
[
"A",
":",
"func",
":",
".",
"check",
"that",
"checks",
"if",
"the",
"channel",
"is",
"a",
"NSFW",
"channel",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1566-L1582
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
cooldown
|
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
|
python
|
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
|
[
"def",
"cooldown",
"(",
"rate",
",",
"per",
",",
"type",
"=",
"BucketType",
".",
"default",
")",
":",
"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"
] |
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.
|
[
"A",
"decorator",
"that",
"adds",
"a",
"cooldown",
"to",
"a",
":",
"class",
":",
".",
"Command",
"or",
"its",
"subclasses",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1584-L1622
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Command.update
|
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))
|
python
|
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))
|
[
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__init__",
"(",
"self",
".",
"callback",
",",
"*",
"*",
"dict",
"(",
"self",
".",
"__original_kwargs__",
",",
"*",
"*",
"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.
|
[
"Updates",
":",
"class",
":",
"Command",
"instance",
"with",
"updated",
"attribute",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L277-L284
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Command.copy
|
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)
|
python
|
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)
|
[
"def",
"copy",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"callback",
",",
"*",
"*",
"self",
".",
"__original_kwargs__",
")",
"return",
"self",
".",
"_ensure_assignment_on_copy",
"(",
"ret",
")"
] |
Creates a copy of this :class:`Command`.
|
[
"Creates",
"a",
"copy",
"of",
"this",
":",
"class",
":",
"Command",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L299-L302
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Command.clean_params
|
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
|
python
|
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
|
[
"def",
"clean_params",
"(",
"self",
")",
":",
"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 parameter OrderedDict without the context or self parameters.
Useful for inspecting signature.
|
[
"Retrieves",
"the",
"parameter",
"OrderedDict",
"without",
"the",
"context",
"or",
"self",
"parameters",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L488-L504
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Command.full_parent_name
|
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))
|
python
|
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))
|
[
"def",
"full_parent_name",
"(",
"self",
")",
":",
"entries",
"=",
"[",
"]",
"command",
"=",
"self",
"while",
"command",
".",
"parent",
"is",
"not",
"None",
":",
"command",
"=",
"command",
".",
"parent",
"entries",
".",
"append",
"(",
"command",
".",
"name",
")",
"return",
"' '",
".",
"join",
"(",
"reversed",
"(",
"entries",
")",
")"
] |
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``.
|
[
"Retrieves",
"the",
"fully",
"qualified",
"parent",
"command",
"name",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L507-L519
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Command.parents
|
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
|
python
|
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
|
[
"def",
"parents",
"(",
"self",
")",
":",
"entries",
"=",
"[",
"]",
"command",
"=",
"self",
"while",
"command",
".",
"parent",
"is",
"not",
"None",
":",
"command",
"=",
"command",
".",
"parent",
"entries",
".",
"append",
"(",
"command",
")",
"return",
"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
|
[
"Retrieves",
"the",
"parents",
"of",
"this",
"command",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L522-L537
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Command.qualified_name
|
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
|
python
|
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
|
[
"def",
"qualified_name",
"(",
"self",
")",
":",
"parent",
"=",
"self",
".",
"full_parent_name",
"if",
"parent",
":",
"return",
"parent",
"+",
"' '",
"+",
"self",
".",
"name",
"else",
":",
"return",
"self",
".",
"name"
] |
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``.
|
[
"Retrieves",
"the",
"fully",
"qualified",
"command",
"name",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L552-L564
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
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
|
python
|
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
|
[
"def",
"is_on_cooldown",
"(",
"self",
",",
"ctx",
")",
":",
"if",
"not",
"self",
".",
"_buckets",
".",
"valid",
":",
"return",
"False",
"bucket",
"=",
"self",
".",
"_buckets",
".",
"get_bucket",
"(",
"ctx",
".",
"message",
")",
"return",
"bucket",
".",
"get_tokens",
"(",
")",
"==",
"0"
] |
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.
|
[
"Checks",
"whether",
"the",
"command",
"is",
"currently",
"on",
"cooldown",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L686-L703
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Command.reset_cooldown
|
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()
|
python
|
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()
|
[
"def",
"reset_cooldown",
"(",
"self",
",",
"ctx",
")",
":",
"if",
"self",
".",
"_buckets",
".",
"valid",
":",
"bucket",
"=",
"self",
".",
"_buckets",
".",
"get_bucket",
"(",
"ctx",
".",
"message",
")",
"bucket",
".",
"reset",
"(",
")"
] |
Resets the cooldown on this command.
Parameters
-----------
ctx: :class:`.Context`
The invocation context to reset the cooldown under.
|
[
"Resets",
"the",
"cooldown",
"on",
"this",
"command",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L705-L715
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Command.error
|
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
|
python
|
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
|
[
"def",
"error",
"(",
"self",
",",
"coro",
")",
":",
"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 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.
|
[
"A",
"decorator",
"that",
"registers",
"a",
"coroutine",
"as",
"a",
"local",
"error",
"handler",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L744-L766
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Command.before_invoke
|
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
|
python
|
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
|
[
"def",
"before_invoke",
"(",
"self",
",",
"coro",
")",
":",
"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 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.
|
[
"A",
"decorator",
"that",
"registers",
"a",
"coroutine",
"as",
"a",
"pre",
"-",
"invoke",
"hook",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L768-L793
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Command.after_invoke
|
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
|
python
|
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
|
[
"def",
"after_invoke",
"(",
"self",
",",
"coro",
")",
":",
"if",
"not",
"asyncio",
".",
"iscoroutinefunction",
"(",
"coro",
")",
":",
"raise",
"TypeError",
"(",
"'The post-invoke hook must be a coroutine.'",
")",
"self",
".",
"_after_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.
|
[
"A",
"decorator",
"that",
"registers",
"a",
"coroutine",
"as",
"a",
"post",
"-",
"invoke",
"hook",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L795-L820
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Command.short_doc
|
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 ''
|
python
|
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 ''
|
[
"def",
"short_doc",
"(",
"self",
")",
":",
"if",
"self",
".",
"brief",
"is",
"not",
"None",
":",
"return",
"self",
".",
"brief",
"if",
"self",
".",
"help",
"is",
"not",
"None",
":",
"return",
"self",
".",
"help",
".",
"split",
"(",
"'\\n'",
",",
"1",
")",
"[",
"0",
"]",
"return",
"''"
] |
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.
|
[
"Gets",
"the",
"short",
"documentation",
"of",
"a",
"command",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L828-L839
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Command.signature
|
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)
|
python
|
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)
|
[
"def",
"signature",
"(",
"self",
")",
":",
"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",
")"
] |
Returns a POSIX-like signature useful for help command output.
|
[
"Returns",
"a",
"POSIX",
"-",
"like",
"signature",
"useful",
"for",
"help",
"command",
"output",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L853-L887
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Command.can_run
|
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
|
python
|
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
|
[
"async",
"def",
"can_run",
"(",
"self",
",",
"ctx",
")",
":",
"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"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L889-L934
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
GroupMixin.add_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
|
python
|
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
|
[
"def",
"add_command",
"(",
"self",
",",
"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"
] |
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`.
|
[
"Adds",
"a",
":",
"class",
":",
".",
"Command",
"or",
"its",
"subclasses",
"into",
"the",
"internal",
"list",
"of",
"commands",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L965-L998
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
GroupMixin.remove_command
|
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
|
python
|
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
|
[
"def",
"remove_command",
"(",
"self",
",",
"name",
")",
":",
"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"
] |
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.
|
[
"Remove",
"a",
":",
"class",
":",
".",
"Command",
"or",
"subclasses",
"from",
"the",
"internal",
"list",
"of",
"commands",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1000-L1030
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
GroupMixin.walk_commands
|
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()
|
python
|
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()
|
[
"def",
"walk_commands",
"(",
"self",
")",
":",
"for",
"command",
"in",
"tuple",
"(",
"self",
".",
"all_commands",
".",
"values",
"(",
")",
")",
":",
"yield",
"command",
"if",
"isinstance",
"(",
"command",
",",
"GroupMixin",
")",
":",
"yield",
"from",
"command",
".",
"walk_commands",
"(",
")"
] |
An iterator that recursively walks through all commands and subcommands.
|
[
"An",
"iterator",
"that",
"recursively",
"walks",
"through",
"all",
"commands",
"and",
"subcommands",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1032-L1037
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
GroupMixin.get_command
|
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
|
python
|
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
|
[
"def",
"get_command",
"(",
"self",
",",
"name",
")",
":",
"# 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"
] |
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``.
|
[
"Get",
"a",
":",
"class",
":",
".",
"Command",
"or",
"subclasses",
"from",
"the",
"internal",
"list",
"of",
"commands",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1039-L1075
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
GroupMixin.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
|
python
|
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
|
[
"def",
"command",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'parent'",
",",
"self",
")",
"result",
"=",
"command",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"(",
"func",
")",
"self",
".",
"add_command",
"(",
"result",
")",
"return",
"result",
"return",
"decorator"
] |
A shortcut decorator that invokes :func:`.command` and adds it to
the internal command list via :meth:`~.GroupMixin.add_command`.
|
[
"A",
"shortcut",
"decorator",
"that",
"invokes",
":",
"func",
":",
".",
"command",
"and",
"adds",
"it",
"to",
"the",
"internal",
"command",
"list",
"via",
":",
"meth",
":",
"~",
".",
"GroupMixin",
".",
"add_command",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1077-L1087
|
train
|
Rapptz/discord.py
|
discord/ext/commands/core.py
|
Group.copy
|
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
|
python
|
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
|
[
"def",
"copy",
"(",
"self",
")",
":",
"ret",
"=",
"super",
"(",
")",
".",
"copy",
"(",
")",
"for",
"cmd",
"in",
"self",
".",
"commands",
":",
"ret",
".",
"add_command",
"(",
"cmd",
".",
"copy",
"(",
")",
")",
"return",
"ret"
] |
Creates a copy of this :class:`Group`.
|
[
"Creates",
"a",
"copy",
"of",
"this",
":",
"class",
":",
"Group",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1127-L1132
|
train
|
Rapptz/discord.py
|
discord/asset.py
|
Asset.read
|
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)
|
python
|
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)
|
[
"async",
"def",
"read",
"(",
"self",
")",
":",
"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|
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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/asset.py#L133-L166
|
train
|
Rapptz/discord.py
|
discord/asset.py
|
Asset.save
|
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)
|
python
|
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)
|
[
"async",
"def",
"save",
"(",
"self",
",",
"fp",
",",
"*",
",",
"seek_begin",
"=",
"True",
")",
":",
"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",
")"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/asset.py#L168-L198
|
train
|
Rapptz/discord.py
|
discord/gateway.py
|
DiscordWebSocket.from_client
|
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
|
python
|
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
|
[
"async",
"def",
"from_client",
"(",
"cls",
",",
"client",
",",
"*",
",",
"shard_id",
"=",
"None",
",",
"session",
"=",
"None",
",",
"sequence",
"=",
"None",
",",
"resume",
"=",
"False",
")",
":",
"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"
] |
Creates a main websocket for Discord from a :class:`Client`.
This is for internal use only.
|
[
"Creates",
"a",
"main",
"websocket",
"for",
"Discord",
"from",
"a",
":",
"class",
":",
"Client",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L219-L257
|
train
|
Rapptz/discord.py
|
discord/gateway.py
|
DiscordWebSocket.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
|
python
|
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
|
[
"def",
"wait_for",
"(",
"self",
",",
"event",
",",
"predicate",
",",
"result",
"=",
"None",
")",
":",
"future",
"=",
"self",
".",
"loop",
".",
"create_future",
"(",
")",
"entry",
"=",
"EventListener",
"(",
"event",
"=",
"event",
",",
"predicate",
"=",
"predicate",
",",
"result",
"=",
"result",
",",
"future",
"=",
"future",
")",
"self",
".",
"_dispatch_listeners",
".",
"append",
"(",
"entry",
")",
"return",
"future"
] |
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.
|
[
"Waits",
"for",
"a",
"DISPATCH",
"d",
"event",
"that",
"meets",
"the",
"predicate",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L259-L282
|
train
|
Rapptz/discord.py
|
discord/gateway.py
|
DiscordWebSocket.identify
|
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)
|
python
|
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)
|
[
"async",
"def",
"identify",
"(",
"self",
")",
":",
"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 IDENTIFY packet.
|
[
"Sends",
"the",
"IDENTIFY",
"packet",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L284-L319
|
train
|
Rapptz/discord.py
|
discord/gateway.py
|
DiscordWebSocket.resume
|
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)
|
python
|
async def resume(self):
"""Sends the RESUME packet."""
payload = {
'op': self.RESUME,
'd': {
'seq': self.sequence,
'session_id': self.session_id,
'token': self.token
}
}
await self.send_as_json(payload)
log.info('Shard ID %s has sent the RESUME payload.', self.shard_id)
|
[
"async",
"def",
"resume",
"(",
"self",
")",
":",
"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",
")"
] |
Sends the RESUME packet.
|
[
"Sends",
"the",
"RESUME",
"packet",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L321-L333
|
train
|
Rapptz/discord.py
|
discord/gateway.py
|
DiscordWebSocket.poll_event
|
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
|
python
|
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
|
[
"async",
"def",
"poll_event",
"(",
"self",
")",
":",
"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"
] |
Polls for a DISPATCH event and handles the general gateway loop.
Raises
------
ConnectionClosed
The websocket connection was terminated for unhandled reasons.
|
[
"Polls",
"for",
"a",
"DISPATCH",
"event",
"and",
"handles",
"the",
"general",
"gateway",
"loop",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L460-L477
|
train
|
Rapptz/discord.py
|
discord/gateway.py
|
DiscordVoiceWebSocket.from_client
|
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
|
python
|
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
|
[
"async",
"def",
"from_client",
"(",
"cls",
",",
"client",
",",
"*",
",",
"resume",
"=",
"False",
")",
":",
"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"
] |
Creates a voice websocket for the :class:`VoiceClient`.
|
[
"Creates",
"a",
"voice",
"websocket",
"for",
"the",
":",
"class",
":",
"VoiceClient",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L625-L638
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
Paginator.clear
|
def clear(self):
"""Clears the paginator to have no pages."""
if self.prefix is not None:
self._current_page = [self.prefix]
self._count = len(self.prefix) + 1 # prefix + newline
else:
self._current_page = []
self._count = 0
self._pages = []
|
python
|
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 = []
|
[
"def",
"clear",
"(",
"self",
")",
":",
"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",
"=",
"[",
"]"
] |
Clears the paginator to have no pages.
|
[
"Clears",
"the",
"paginator",
"to",
"have",
"no",
"pages",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L89-L97
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
Paginator.add_line
|
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
|
python
|
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
|
[
"def",
"add_line",
"(",
"self",
",",
"line",
"=",
"''",
",",
"*",
",",
"empty",
"=",
"False",
")",
":",
"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"
] |
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`.
|
[
"Adds",
"a",
"line",
"to",
"the",
"current",
"page",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L103-L133
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
Paginator.close_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
|
python
|
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
|
[
"def",
"close_page",
"(",
"self",
")",
":",
"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"
] |
Prematurely terminate a page.
|
[
"Prematurely",
"terminate",
"a",
"page",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L135-L146
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
HelpCommand.get_bot_mapping
|
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
|
python
|
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
|
[
"def",
"get_bot_mapping",
"(",
"self",
")",
":",
"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"
] |
Retrieves the bot mapping passed to :meth:`send_bot_help`.
|
[
"Retrieves",
"the",
"bot",
"mapping",
"passed",
"to",
":",
"meth",
":",
"send_bot_help",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L325-L333
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
HelpCommand.clean_prefix
|
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)
|
python
|
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)
|
[
"def",
"clean_prefix",
"(",
"self",
")",
":",
"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",
")"
] |
The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
|
[
"The",
"cleaned",
"up",
"invoke",
"prefix",
".",
"i",
".",
"e",
".",
"mentions",
"are"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L336-L343
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
HelpCommand.invoked_with
|
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
|
python
|
def invoked_with(self):
"""Similar to :attr:`Context.invoked_with` except properly handles
the case where :meth:`Context.send_help` is used.
If the help command was used regularly then this returns
the :attr:`Context.invoked_with` attribute. Otherwise, if
it the help command was called using :meth:`Context.send_help`
then it returns the internal command name of the help command.
Returns
---------
:class:`str`
The command name that triggered this invocation.
"""
command_name = self._command_impl.name
ctx = self.context
if ctx is None or ctx.command is None or ctx.command.qualified_name != command_name:
return command_name
return ctx.invoked_with
|
[
"def",
"invoked_with",
"(",
"self",
")",
":",
"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"
] |
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.
|
[
"Similar",
"to",
":",
"attr",
":",
"Context",
".",
"invoked_with",
"except",
"properly",
"handles",
"the",
"case",
"where",
":",
"meth",
":",
"Context",
".",
"send_help",
"is",
"used",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L346-L364
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
HelpCommand.get_command_signature
|
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)
|
python
|
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)
|
[
"def",
"get_command_signature",
"(",
"self",
",",
"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",
")"
] |
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.
|
[
"Retrieves",
"the",
"signature",
"portion",
"of",
"the",
"help",
"page",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L366-L390
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
HelpCommand.remove_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)
|
python
|
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)
|
[
"def",
"remove_mentions",
"(",
"self",
",",
"string",
")",
":",
"def",
"replace",
"(",
"obj",
",",
"*",
",",
"transforms",
"=",
"self",
".",
"MENTION_TRANSFORMS",
")",
":",
"return",
"transforms",
".",
"get",
"(",
"obj",
".",
"group",
"(",
"0",
")",
",",
"'@invalid'",
")",
"return",
"self",
".",
"MENTION_PATTERN",
".",
"sub",
"(",
"replace",
",",
"string",
")"
] |
Removes mentions from the string to prevent abuse.
This includes ``@everyone``, ``@here``, member mentions and role mentions.
|
[
"Removes",
"mentions",
"from",
"the",
"string",
"to",
"prevent",
"abuse",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L392-L401
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
HelpCommand.subcommand_not_found
|
def subcommand_not_found(self, command, string):
"""|maybecoro|
A method called when a command did not have a subcommand requested in the help command.
This is useful to override for i18n.
Defaults to either:
- ``'Command "{command.qualified_name}" has no subcommands.'``
- If there is no subcommand in the ``command`` parameter.
- ``'Command "{command.qualified_name}" has no subcommand named {string}'``
- If the ``command`` parameter has subcommands but not one named ``string``.
Parameters
------------
command: :class:`Command`
The command that did not have the subcommand requested.
string: :class:`str`
The string that contains the invalid subcommand. Note that this has
had mentions removed to prevent abuse.
Returns
---------
:class:`str`
The string to use when the command did not have the subcommand requested.
"""
if isinstance(command, Group) and len(command.all_commands) > 0:
return 'Command "{0.qualified_name}" has no subcommand named {1}'.format(command, string)
return 'Command "{0.qualified_name}" has no subcommands.'.format(command)
|
python
|
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)
|
[
"def",
"subcommand_not_found",
"(",
"self",
",",
"command",
",",
"string",
")",
":",
"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",
")"
] |
|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.
|
[
"|maybecoro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L450-L478
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
HelpCommand.filter_commands
|
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
|
python
|
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
|
[
"async",
"def",
"filter_commands",
"(",
"self",
",",
"commands",
",",
"*",
",",
"sort",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"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"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L480-L530
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
HelpCommand.get_max_size
|
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)
|
python
|
def get_max_size(self, commands):
"""Returns the largest name length of the specified command list.
Parameters
------------
commands: Sequence[:class:`Command`]
A sequence of commands to check for the largest size.
Returns
--------
:class:`int`
The maximum width of the commands.
"""
as_lengths = (
discord.utils._string_width(c.name)
for c in commands
)
return max(as_lengths, default=0)
|
[
"def",
"get_max_size",
"(",
"self",
",",
"commands",
")",
":",
"as_lengths",
"=",
"(",
"discord",
".",
"utils",
".",
"_string_width",
"(",
"c",
".",
"name",
")",
"for",
"c",
"in",
"commands",
")",
"return",
"max",
"(",
"as_lengths",
",",
"default",
"=",
"0",
")"
] |
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.
|
[
"Returns",
"the",
"largest",
"name",
"length",
"of",
"the",
"specified",
"command",
"list",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L532-L550
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
HelpCommand.command_callback
|
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)
|
python
|
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)
|
[
"async",
"def",
"command_callback",
"(",
"self",
",",
"ctx",
",",
"*",
",",
"command",
"=",
"None",
")",
":",
"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",
")"
] |
|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`
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L754-L812
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
DefaultHelpCommand.shorten_text
|
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
|
python
|
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
|
[
"def",
"shorten_text",
"(",
"self",
",",
"text",
")",
":",
"if",
"len",
"(",
"text",
")",
">",
"self",
".",
"width",
":",
"return",
"text",
"[",
":",
"self",
".",
"width",
"-",
"3",
"]",
"+",
"'...'",
"return",
"text"
] |
Shortens text to fit into the :attr:`width`.
|
[
"Shortens",
"text",
"to",
"fit",
"into",
"the",
":",
"attr",
":",
"width",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L865-L869
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
DefaultHelpCommand.add_indented_commands
|
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))
|
python
|
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))
|
[
"def",
"add_indented_commands",
"(",
"self",
",",
"commands",
",",
"*",
",",
"heading",
",",
"max_size",
"=",
"None",
")",
":",
"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",
")",
")"
] |
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.
|
[
"Indents",
"a",
"list",
"of",
"commands",
"after",
"the",
"specified",
"heading",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L877-L911
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.