partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
Messageable.fetch_message
|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.
discord/abc.py
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): """|coro| Retrieves a single :class:`.Message` from the destination. This can only be used by bot accounts. Parameters ------------ id: :class:`int` The message ID to look for. Raises -------- :exc:`.NotFound` The specified message was not found. :exc:`.Forbidden` You do not have the permissions required to get a message. :exc:`.HTTPException` Retrieving the message failed. Returns -------- :class:`.Message` The message asked for. """ channel = await self._get_channel() data = await self._state.http.get_message(channel.id, id) return self._state.create_message(channel=channel, data=data)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L860-L889
[ "async", "def", "fetch_message", "(", "self", ",", "id", ")", ":", "channel", "=", "await", "self", ".", "_get_channel", "(", ")", "data", "=", "await", "self", ".", "_state", ".", "http", ".", "get_message", "(", "channel", ".", "id", ",", "id", ")"...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Messageable.pins
|coro| Returns a :class:`list` of :class:`.Message` that are currently pinned. Raises ------- :exc:`.HTTPException` Retrieving the pinned messages failed.
discord/abc.py
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): """|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]
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L891-L905
[ "async", "def", "pins", "(", "self", ")", ":", "channel", "=", "await", "self", ".", "_get_channel", "(", ")", "state", "=", "self", ".", "_state", "data", "=", "await", "state", ".", "http", ".", "pins_from", "(", "channel", ".", "id", ")", "return"...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Messageable.history
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.
discord/abc.py
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 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)
[ "Return", "an", ":", "class", ":", ".", "AsyncIterator", "that", "enables", "receiving", "the", "destination", "s", "message", "history", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L907-L962
[ "def", "history", "(", "self", ",", "*", ",", "limit", "=", "100", ",", "before", "=", "None", ",", "after", "=", "None", ",", "around", "=", "None", ",", "oldest_first", "=", "None", ")", ":", "return", "HistoryIterator", "(", "self", ",", "limit", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Connectable.connect
|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.
discord/abc.py
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): """|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
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L983-L1031
[ "async", "def", "connect", "(", "self", ",", "*", ",", "timeout", "=", "60.0", ",", "reconnect", "=", "True", ")", ":", "key_id", ",", "_", "=", "self", ".", "_get_voice_client_key", "(", ")", "state", "=", "self", ".", "_state", "if", "state", ".", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
PartialEmoji.url
:class:`Asset`:Returns an asset of the emoji, if it is custom.
discord/emoji.py
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): """: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)
[ ":", "class", ":", "Asset", ":", "Returns", "an", "asset", "of", "the", "emoji", "if", "it", "is", "custom", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/emoji.py#L116-L123
[ "def", "url", "(", "self", ")", ":", "if", "self", ".", "is_unicode_emoji", "(", ")", ":", "return", "Asset", "(", "self", ".", "_state", ")", "_format", "=", "'gif'", "if", "self", ".", "animated", "else", "'png'", "url", "=", "\"https://cdn.discordapp....
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Emoji.roles
List[:class:`Role`]: A :class:`list` of roles that is allowed to use this emoji. If roles is empty, the emoji is unrestricted.
discord/emoji.py
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): """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)]
[ "List", "[", ":", "class", ":", "Role", "]", ":", "A", ":", "class", ":", "list", "of", "roles", "that", "is", "allowed", "to", "use", "this", "emoji", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/emoji.py#L229-L238
[ "def", "roles", "(", "self", ")", ":", "guild", "=", "self", ".", "guild", "if", "guild", "is", "None", ":", "return", "[", "]", "return", "[", "role", "for", "role", "in", "guild", ".", "roles", "if", "self", ".", "_roles", ".", "has", "(", "rol...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Emoji.delete
|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.
discord/emoji.py
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): """|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)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/emoji.py#L245-L266
[ "async", "def", "delete", "(", "self", ",", "*", ",", "reason", "=", "None", ")", ":", "await", "self", ".", "_state", ".", "http", ".", "delete_custom_emoji", "(", "self", ".", "guild", ".", "id", ",", "self", ".", "id", ",", "reason", "=", "reaso...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Emoji.edit
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.
discord/emoji.py
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): 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)
[ "r", "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/emoji.py#L268-L295
[ "async", "def", "edit", "(", "self", ",", "*", ",", "name", ",", "roles", "=", "None", ",", "reason", "=", "None", ")", ":", "if", "roles", ":", "roles", "=", "[", "role", ".", "id", "for", "role", "in", "roles", "]", "await", "self", ".", "_st...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
loop
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.
discord/ext/tasks/__init__.py
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): """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
[ "A", "decorator", "that", "schedules", "a", "task", "in", "the", "background", "for", "you", "with", "optional", "reconnect", "logic", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L238-L276
[ "def", "loop", "(", "*", ",", "seconds", "=", "0", ",", "minutes", "=", "0", ",", "hours", "=", "0", ",", "count", "=", "None", ",", "reconnect", "=", "True", ",", "loop", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "retur...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Loop.start
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.
discord/ext/tasks/__init__.py
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): r"""Starts the internal task in the event loop. Parameters ------------ \*args The arguments to to use. \*\*kwargs The keyword arguments to use. Raises -------- RuntimeError A task has already been launched. Returns --------- :class:`asyncio.Task` The task that has been created. """ if self._task is not None: raise RuntimeError('Task is already launched.') if self._injected is not None: args = (self._injected, *args) self._task = self.loop.create_task(self._loop(*args, **kwargs)) return self._task
[ "r", "Starts", "the", "internal", "task", "in", "the", "event", "loop", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L101-L129
[ "def", "start", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_task", "is", "not", "None", ":", "raise", "RuntimeError", "(", "'Task is already launched.'", ")", "if", "self", ".", "_injected", "is", "not", "None...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Loop.add_exception_type
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`.
discord/ext/tasks/__init__.py
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): 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)
[ "r", "Adds", "an", "exception", "type", "to", "be", "handled", "during", "the", "reconnect", "logic", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L137-L163
[ "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...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Loop.remove_exception_type
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.
discord/ext/tasks/__init__.py
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): """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
[ "Removes", "an", "exception", "type", "from", "being", "handled", "during", "the", "reconnect", "logic", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L174-L189
[ "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", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Loop.before_loop
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.
discord/ext/tasks/__init__.py
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): """A function that also acts as a decorator to register a coroutine to be called before the loop starts running. This is useful if you want to wait for some bot state before the loop starts, such as :meth:`discord.Client.wait_until_ready`. Parameters ------------ coro: :term:`py:awaitable` The coroutine to register before the loop runs. Raises ------- TypeError The function was not a coroutine. """ if not (inspect.iscoroutinefunction(coro) or inspect.isawaitable(coro)): raise TypeError('Expected coroutine or awaitable, received {0.__name__!r}.'.format(type(coro))) self._before_loop = coro
[ "A", "function", "that", "also", "acts", "as", "a", "decorator", "to", "register", "a", "coroutine", "to", "be", "called", "before", "the", "loop", "starts", "running", ".", "This", "is", "useful", "if", "you", "want", "to", "wait", "for", "some", "bot",...
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L195-L215
[ "def", "before_loop", "(", "self", ",", "coro", ")", ":", "if", "not", "(", "inspect", ".", "iscoroutinefunction", "(", "coro", ")", "or", "inspect", ".", "isawaitable", "(", "coro", ")", ")", ":", "raise", "TypeError", "(", "'Expected coroutine or awaitable...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Loop.after_loop
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.
discord/ext/tasks/__init__.py
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): """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
[ "A", "function", "that", "also", "acts", "as", "a", "decorator", "to", "register", "a", "coroutine", "to", "be", "called", "after", "the", "loop", "finished", "running", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/tasks/__init__.py#L218-L236
[ "def", "after_loop", "(", "self", ",", "coro", ")", ":", "if", "not", "(", "inspect", ".", "iscoroutinefunction", "(", "coro", ")", "or", "inspect", ".", "isawaitable", "(", "coro", ")", ")", ":", "raise", "TypeError", "(", "'Expected coroutine or awaitable,...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Context.invoke
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.
discord/ext/commands/context.py
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): 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
[ "r", "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/context.py#L89-L128
[ "async", "def", "invoke", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "command", "=", "args", "[", "0", "]", "except", "IndexError", ":", "raise", "TypeError", "(", "'Missing command to invoke.'", ")", "from", "None", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Context.reinvoke
|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.
discord/ext/commands/context.py
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): """|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
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/context.py#L130-L182
[ "async", "def", "reinvoke", "(", "self", ",", "*", ",", "call_hooks", "=", "False", ",", "restart", "=", "True", ")", ":", "cmd", "=", "self", ".", "command", "view", "=", "self", ".", "view", "if", "cmd", "is", "None", ":", "raise", "ValueError", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Context.me
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.
discord/ext/commands/context.py
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): """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
[ "Similar", "to", ":", "attr", ":", ".", "Guild", ".", "me", "except", "it", "may", "return", "the", ":", "class", ":", ".", "ClientUser", "in", "private", "message", "contexts", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/context.py#L216-L218
[ "def", "me", "(", "self", ")", ":", "return", "self", ".", "guild", ".", "me", "if", "self", ".", "guild", "is", "not", "None", "else", "self", ".", "bot", ".", "user" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Context.send_help
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.
discord/ext/commands/context.py
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): """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
[ "send_help", "(", "entity", "=", "<bot", ">", ")" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/context.py#L226-L293
[ "async", "def", "send_help", "(", "self", ",", "*", "args", ")", ":", "from", ".", "core", "import", "Group", ",", "Command", "bot", "=", "self", ".", "bot", "cmd", "=", "bot", ".", "help_command", "if", "cmd", "is", "None", ":", "return", "None", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
ExponentialBackoff.delay
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.
discord/backoff.py
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): """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)
[ "Compute", "the", "next", "delay" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/backoff.py#L66-L85
[ "def", "delay", "(", "self", ")", ":", "invocation", "=", "time", ".", "monotonic", "(", ")", "interval", "=", "invocation", "-", "self", ".", "_last_invocation", "self", ".", "_last_invocation", "=", "invocation", "if", "interval", ">", "self", ".", "_res...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Permissions.is_subset
Returns True if self has the same or fewer permissions as other.
discord/permissions.py
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): """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__))
[ "Returns", "True", "if", "self", "has", "the", "same", "or", "fewer", "permissions", "as", "other", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/permissions.py#L99-L104
[ "def", "is_subset", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Permissions", ")", ":", "return", "(", "self", ".", "value", "&", "other", ".", "value", ")", "==", "self", ".", "value", "else", ":", "raise", "TypeErro...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Permissions.update
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.
discord/permissions.py
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): 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)
[ "r", "Bulk", "updates", "this", "permission", "object", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/permissions.py#L171-L190
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "try", ":", "is_property", "=", "isinstance", "(", "getattr", "(", "self", ".", "__class__", ",", "key", ")", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
AuditLogEntry.changes
:class:`AuditLogChanges`: The list of changes this entry has.
discord/audit_logs.py
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): """:class:`AuditLogChanges`: The list of changes this entry has.""" obj = AuditLogChanges(self, self._changes) del self._changes return obj
[ ":", "class", ":", "AuditLogChanges", ":", "The", "list", "of", "changes", "this", "entry", "has", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/audit_logs.py#L286-L290
[ "def", "changes", "(", "self", ")", ":", "obj", "=", "AuditLogChanges", "(", "self", ",", "self", ".", "_changes", ")", "del", "self", ".", "_changes", "return", "obj" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
command
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.
discord/ext/commands/core.py
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): """A decorator that transforms a function into a :class:`.Command` or if called with :func:`.group`, :class:`.Group`. By default the ``help`` attribute is received automatically from the docstring of the function and is cleaned up with the use of ``inspect.cleandoc``. If the docstring is ``bytes``, then it is decoded into :class:`str` using utf-8 encoding. All checks added using the :func:`.check` & co. decorators are added into the function. There is no way to supply your own checks through this decorator. Parameters ----------- name: :class:`str` The name to create the command with. By default this uses the function name unchanged. cls The class to construct with. By default this is :class:`.Command`. You usually do not change this. attrs Keyword arguments to pass into the construction of the class denoted by ``cls``. Raises ------- TypeError If the function is not a coroutine or is already a command. """ if cls is None: cls = Command def decorator(func): if isinstance(func, Command): raise TypeError('Callback is already a command.') return cls(func, name=name, **attrs) return decorator
[ "A", "decorator", "that", "transforms", "a", "function", "into", "a", ":", "class", ":", ".", "Command", "or", "if", "called", "with", ":", "func", ":", ".", "group", ":", "class", ":", ".", "Group", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1200-L1238
[ "def", "command", "(", "name", "=", "None", ",", "cls", "=", "None", ",", "*", "*", "attrs", ")", ":", "if", "cls", "is", "None", ":", "cls", "=", "Command", "def", "decorator", "(", "func", ")", ":", "if", "isinstance", "(", "func", ",", "Comman...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
group
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.
discord/ext/commands/core.py
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): """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)
[ "A", "decorator", "that", "transforms", "a", "function", "into", "a", ":", "class", ":", ".", "Group", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1240-L1251
[ "def", "group", "(", "name", "=", "None", ",", "*", "*", "attrs", ")", ":", "attrs", ".", "setdefault", "(", "'cls'", ",", "Group", ")", "return", "command", "(", "name", "=", "name", ",", "*", "*", "attrs", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
check
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.
discord/ext/commands/core.py
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): 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
[ "r", "A", "decorator", "that", "adds", "a", "check", "to", "the", ":", "class", ":", ".", "Command", "or", "its", "subclasses", ".", "These", "checks", "could", "be", "accessed", "via", ":", "attr", ":", ".", "Command", ".", "checks", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1253-L1316
[ "def", "check", "(", "predicate", ")", ":", "def", "decorator", "(", "func", ")", ":", "if", "isinstance", "(", "func", ",", "Command", ")", ":", "func", ".", "checks", ".", "append", "(", "predicate", ")", "else", ":", "if", "not", "hasattr", "(", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
has_role
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.
discord/ext/commands/core.py
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): """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)
[ "A", ":", "func", ":", ".", "check", "that", "is", "added", "that", "checks", "if", "the", "member", "invoking", "the", "command", "has", "the", "role", "specified", "via", "the", "name", "or", "ID", "specified", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1318-L1357
[ "def", "has_role", "(", "item", ")", ":", "def", "predicate", "(", "ctx", ")", ":", "if", "not", "isinstance", "(", "ctx", ".", "channel", ",", "discord", ".", "abc", ".", "GuildChannel", ")", ":", "raise", "NoPrivateMessage", "(", ")", "if", "isinstan...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
has_any_role
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')
discord/ext/commands/core.py
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): 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)
[ "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", "...
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1359-L1399
[ "def", "has_any_role", "(", "*", "items", ")", ":", "def", "predicate", "(", "ctx", ")", ":", "if", "not", "isinstance", "(", "ctx", ".", "channel", ",", "discord", ".", "abc", ".", "GuildChannel", ")", ":", "raise", "NoPrivateMessage", "(", ")", "gett...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
bot_has_role
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`
discord/ext/commands/core.py
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): """Similar to :func:`.has_role` except checks if the bot itself has the role. This check raises one of two special exceptions, :exc:`.BotMissingRole` if the bot is missing the role, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1.0 Raise :exc:`.BotMissingRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` """ def predicate(ctx): ch = ctx.channel if not isinstance(ch, discord.abc.GuildChannel): raise NoPrivateMessage() me = ch.guild.me if isinstance(item, int): role = discord.utils.get(me.roles, id=item) else: role = discord.utils.get(me.roles, name=item) if role is None: raise BotMissingRole(item) return True return check(predicate)
[ "Similar", "to", ":", "func", ":", ".", "has_role", "except", "checks", "if", "the", "bot", "itself", "has", "the", "role", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1401-L1428
[ "def", "bot_has_role", "(", "item", ")", ":", "def", "predicate", "(", "ctx", ")", ":", "ch", "=", "ctx", ".", "channel", "if", "not", "isinstance", "(", "ch", ",", "discord", ".", "abc", ".", "GuildChannel", ")", ":", "raise", "NoPrivateMessage", "(",...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
bot_has_any_role
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
discord/ext/commands/core.py
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): """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)
[ "Similar", "to", ":", "func", ":", ".", "has_any_role", "except", "checks", "if", "the", "bot", "itself", "has", "any", "of", "the", "roles", "listed", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1430-L1453
[ "def", "bot_has_any_role", "(", "*", "items", ")", ":", "def", "predicate", "(", "ctx", ")", ":", "ch", "=", "ctx", ".", "channel", "if", "not", "isinstance", "(", "ch", ",", "discord", ".", "abc", ".", "GuildChannel", ")", ":", "raise", "NoPrivateMess...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
has_permissions
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.')
discord/ext/commands/core.py
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): """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)
[ "A", ":", "func", ":", ".", "check", "that", "is", "added", "that", "checks", "if", "the", "member", "has", "all", "of", "the", "permissions", "necessary", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1455-L1492
[ "def", "has_permissions", "(", "*", "*", "perms", ")", ":", "def", "predicate", "(", "ctx", ")", ":", "ch", "=", "ctx", ".", "channel", "permissions", "=", "ch", ".", "permissions_for", "(", "ctx", ".", "author", ")", "missing", "=", "[", "perm", "fo...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
bot_has_permissions
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`.
discord/ext/commands/core.py
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): """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)
[ "Similar", "to", ":", "func", ":", ".", "has_permissions", "except", "checks", "if", "the", "bot", "itself", "has", "the", "permissions", "listed", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1494-L1513
[ "def", "bot_has_permissions", "(", "*", "*", "perms", ")", ":", "def", "predicate", "(", "ctx", ")", ":", "guild", "=", "ctx", ".", "guild", "me", "=", "guild", ".", "me", "if", "guild", "is", "not", "None", "else", "ctx", ".", "bot", ".", "user", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
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`.
discord/ext/commands/core.py
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(): """A :func:`.check` that checks if the person invoking this command is the owner of the bot. This is powered by :meth:`.Bot.is_owner`. This check raises a special exception, :exc:`.NotOwner` that is derived from :exc:`.CheckFailure`. """ async def predicate(ctx): if not await ctx.bot.is_owner(ctx.author): raise NotOwner('You do not own this bot.') return True return check(predicate)
[ "A", ":", "func", ":", ".", "check", "that", "checks", "if", "the", "person", "invoking", "this", "command", "is", "the", "owner", "of", "the", "bot", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1549-L1564
[ "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", "...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
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.
discord/ext/commands/core.py
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(): """A :func:`.check` that checks if the channel is a NSFW channel. This check raises a special exception, :exc:`.NSFWChannelRequired` that is derived from :exc:`.CheckFailure`. .. versionchanged:: 1.1.0 Raise :exc:`.NSFWChannelRequired instead of generic :exc:`.CheckFailure`. DM channels will also now pass this check. """ def pred(ctx): ch = ctx.channel if ctx.guild is None or (isinstance(ch, discord.TextChannel) and ch.is_nsfw()): return True raise NSFWChannelRequired(ch) return check(pred)
[ "A", ":", "func", ":", ".", "check", "that", "checks", "if", "the", "channel", "is", "a", "NSFW", "channel", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1566-L1582
[ "def", "is_nsfw", "(", ")", ":", "def", "pred", "(", "ctx", ")", ":", "ch", "=", "ctx", ".", "channel", "if", "ctx", ".", "guild", "is", "None", "or", "(", "isinstance", "(", "ch", ",", "discord", ".", "TextChannel", ")", "and", "ch", ".", "is_ns...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
cooldown
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.
discord/ext/commands/core.py
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): """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
[ "A", "decorator", "that", "adds", "a", "cooldown", "to", "a", ":", "class", ":", ".", "Command", "or", "its", "subclasses", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1584-L1622
[ "def", "cooldown", "(", "rate", ",", "per", ",", "type", "=", "BucketType", ".", "default", ")", ":", "def", "decorator", "(", "func", ")", ":", "if", "isinstance", "(", "func", ",", "Command", ")", ":", "func", ".", "_buckets", "=", "CooldownMapping",...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.update
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.
discord/ext/commands/core.py
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): """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))
[ "Updates", ":", "class", ":", "Command", "instance", "with", "updated", "attribute", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L277-L284
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "__init__", "(", "self", ".", "callback", ",", "*", "*", "dict", "(", "self", ".", "__original_kwargs__", ",", "*", "*", "kwargs", ")", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.copy
Creates a copy of this :class:`Command`.
discord/ext/commands/core.py
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): """Creates a copy of this :class:`Command`.""" ret = self.__class__(self.callback, **self.__original_kwargs__) return self._ensure_assignment_on_copy(ret)
[ "Creates", "a", "copy", "of", "this", ":", "class", ":", "Command", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L299-L302
[ "def", "copy", "(", "self", ")", ":", "ret", "=", "self", ".", "__class__", "(", "self", ".", "callback", ",", "*", "*", "self", ".", "__original_kwargs__", ")", "return", "self", ".", "_ensure_assignment_on_copy", "(", "ret", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.clean_params
Retrieves the parameter OrderedDict without the context or self parameters. Useful for inspecting signature.
discord/ext/commands/core.py
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): """Retrieves the parameter OrderedDict without the context or self parameters. Useful for inspecting signature. """ result = self.params.copy() if self.cog is not None: # first parameter is self result.popitem(last=False) try: # first/second parameter is context result.popitem(last=False) except Exception: raise ValueError('Missing context parameter') from None return result
[ "Retrieves", "the", "parameter", "OrderedDict", "without", "the", "context", "or", "self", "parameters", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L488-L504
[ "def", "clean_params", "(", "self", ")", ":", "result", "=", "self", ".", "params", ".", "copy", "(", ")", "if", "self", ".", "cog", "is", "not", "None", ":", "# first parameter is self", "result", ".", "popitem", "(", "last", "=", "False", ")", "try",...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.full_parent_name
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``.
discord/ext/commands/core.py
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): """Retrieves the fully qualified parent command name. This the base command name required to execute it. For example, in ``?one two three`` the parent name would be ``one two``. """ entries = [] command = self while command.parent is not None: command = command.parent entries.append(command.name) return ' '.join(reversed(entries))
[ "Retrieves", "the", "fully", "qualified", "parent", "command", "name", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L507-L519
[ "def", "full_parent_name", "(", "self", ")", ":", "entries", "=", "[", "]", "command", "=", "self", "while", "command", ".", "parent", "is", "not", "None", ":", "command", "=", "command", ".", "parent", "entries", ".", "append", "(", "command", ".", "n...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.parents
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
discord/ext/commands/core.py
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): """Retrieves the parents of this command. If the command has no parents then it returns an empty :class:`list`. For example in commands ``?a b c test``, the parents are ``[c, b, a]``. .. versionadded:: 1.1.0 """ entries = [] command = self while command.parent is not None: command = command.parent entries.append(command) return entries
[ "Retrieves", "the", "parents", "of", "this", "command", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L522-L537
[ "def", "parents", "(", "self", ")", ":", "entries", "=", "[", "]", "command", "=", "self", "while", "command", ".", "parent", "is", "not", "None", ":", "command", "=", "command", ".", "parent", "entries", ".", "append", "(", "command", ")", "return", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.qualified_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``.
discord/ext/commands/core.py
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): """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
[ "Retrieves", "the", "fully", "qualified", "command", "name", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L552-L564
[ "def", "qualified_name", "(", "self", ")", ":", "parent", "=", "self", ".", "full_parent_name", "if", "parent", ":", "return", "parent", "+", "' '", "+", "self", ".", "name", "else", ":", "return", "self", ".", "name" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.is_on_cooldown
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.
discord/ext/commands/core.py
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): """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
[ "Checks", "whether", "the", "command", "is", "currently", "on", "cooldown", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L686-L703
[ "def", "is_on_cooldown", "(", "self", ",", "ctx", ")", ":", "if", "not", "self", ".", "_buckets", ".", "valid", ":", "return", "False", "bucket", "=", "self", ".", "_buckets", ".", "get_bucket", "(", "ctx", ".", "message", ")", "return", "bucket", ".",...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.reset_cooldown
Resets the cooldown on this command. Parameters ----------- ctx: :class:`.Context` The invocation context to reset the cooldown under.
discord/ext/commands/core.py
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): """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()
[ "Resets", "the", "cooldown", "on", "this", "command", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L705-L715
[ "def", "reset_cooldown", "(", "self", ",", "ctx", ")", ":", "if", "self", ".", "_buckets", ".", "valid", ":", "bucket", "=", "self", ".", "_buckets", ".", "get_bucket", "(", "ctx", ".", "message", ")", "bucket", ".", "reset", "(", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.error
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.
discord/ext/commands/core.py
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): """A decorator that registers a coroutine as a local error handler. A local error handler is an :func:`.on_command_error` event limited to a single command. However, the :func:`.on_command_error` is still invoked afterwards as the catch-all. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the local error handler. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The error handler must be a coroutine.') self.on_error = coro return coro
[ "A", "decorator", "that", "registers", "a", "coroutine", "as", "a", "local", "error", "handler", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L744-L766
[ "def", "error", "(", "self", ",", "coro", ")", ":", "if", "not", "asyncio", ".", "iscoroutinefunction", "(", "coro", ")", ":", "raise", "TypeError", "(", "'The error handler must be a coroutine.'", ")", "self", ".", "on_error", "=", "coro", "return", "coro" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.before_invoke
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.
discord/ext/commands/core.py
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): """A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required. This pre-invoke hook takes a sole parameter, a :class:`.Context`. See :meth:`.Bot.before_invoke` for more info. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the pre-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke = coro return coro
[ "A", "decorator", "that", "registers", "a", "coroutine", "as", "a", "pre", "-", "invoke", "hook", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L768-L793
[ "def", "before_invoke", "(", "self", ",", "coro", ")", ":", "if", "not", "asyncio", ".", "iscoroutinefunction", "(", "coro", ")", ":", "raise", "TypeError", "(", "'The pre-invoke hook must be a coroutine.'", ")", "self", ".", "_before_invoke", "=", "coro", "retu...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.after_invoke
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.
discord/ext/commands/core.py
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): """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
[ "A", "decorator", "that", "registers", "a", "coroutine", "as", "a", "post", "-", "invoke", "hook", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L795-L820
[ "def", "after_invoke", "(", "self", ",", "coro", ")", ":", "if", "not", "asyncio", ".", "iscoroutinefunction", "(", "coro", ")", ":", "raise", "TypeError", "(", "'The post-invoke hook must be a coroutine.'", ")", "self", ".", "_after_invoke", "=", "coro", "retur...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.short_doc
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.
discord/ext/commands/core.py
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): """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 ''
[ "Gets", "the", "short", "documentation", "of", "a", "command", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L828-L839
[ "def", "short_doc", "(", "self", ")", ":", "if", "self", ".", "brief", "is", "not", "None", ":", "return", "self", ".", "brief", "if", "self", ".", "help", "is", "not", "None", ":", "return", "self", ".", "help", ".", "split", "(", "'\\n'", ",", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.signature
Returns a POSIX-like signature useful for help command output.
discord/ext/commands/core.py
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): """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)
[ "Returns", "a", "POSIX", "-", "like", "signature", "useful", "for", "help", "command", "output", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L853-L887
[ "def", "signature", "(", "self", ")", ":", "if", "self", ".", "usage", "is", "not", "None", ":", "return", "self", ".", "usage", "params", "=", "self", ".", "clean_params", "if", "not", "params", ":", "return", "''", "result", "=", "[", "]", "for", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Command.can_run
|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.
discord/ext/commands/core.py
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): """|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
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L889-L934
[ "async", "def", "can_run", "(", "self", ",", "ctx", ")", ":", "original", "=", "ctx", ".", "command", "ctx", ".", "command", "=", "self", "try", ":", "if", "not", "await", "ctx", ".", "bot", ".", "can_run", "(", "ctx", ")", ":", "raise", "CheckFail...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
GroupMixin.add_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`.
discord/ext/commands/core.py
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): """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
[ "Adds", "a", ":", "class", ":", ".", "Command", "or", "its", "subclasses", "into", "the", "internal", "list", "of", "commands", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L965-L998
[ "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...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
GroupMixin.remove_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.
discord/ext/commands/core.py
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): """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
[ "Remove", "a", ":", "class", ":", ".", "Command", "or", "subclasses", "from", "the", "internal", "list", "of", "commands", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1000-L1030
[ "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", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
GroupMixin.walk_commands
An iterator that recursively walks through all commands and subcommands.
discord/ext/commands/core.py
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): """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()
[ "An", "iterator", "that", "recursively", "walks", "through", "all", "commands", "and", "subcommands", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1032-L1037
[ "def", "walk_commands", "(", "self", ")", ":", "for", "command", "in", "tuple", "(", "self", ".", "all_commands", ".", "values", "(", ")", ")", ":", "yield", "command", "if", "isinstance", "(", "command", ",", "GroupMixin", ")", ":", "yield", "from", "...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
GroupMixin.get_command
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``.
discord/ext/commands/core.py
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): """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
[ "Get", "a", ":", "class", ":", ".", "Command", "or", "subclasses", "from", "the", "internal", "list", "of", "commands", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1039-L1075
[ "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", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
GroupMixin.command
A shortcut decorator that invokes :func:`.command` and adds it to the internal command list via :meth:`~.GroupMixin.add_command`.
discord/ext/commands/core.py
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): """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
[ "A", "shortcut", "decorator", "that", "invokes", ":", "func", ":", ".", "command", "and", "adds", "it", "to", "the", "internal", "command", "list", "via", ":", "meth", ":", "~", ".", "GroupMixin", ".", "add_command", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1077-L1087
[ "def", "command", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "func", ")", ":", "kwargs", ".", "setdefault", "(", "'parent'", ",", "self", ")", "result", "=", "command", "(", "*", "args", ",", "*", "...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Group.copy
Creates a copy of this :class:`Group`.
discord/ext/commands/core.py
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): """Creates a copy of this :class:`Group`.""" ret = super().copy() for cmd in self.commands: ret.add_command(cmd.copy()) return ret
[ "Creates", "a", "copy", "of", "this", ":", "class", ":", "Group", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1127-L1132
[ "def", "copy", "(", "self", ")", ":", "ret", "=", "super", "(", ")", ".", "copy", "(", ")", "for", "cmd", "in", "self", ".", "commands", ":", "ret", ".", "add_command", "(", "cmd", ".", "copy", "(", ")", ")", "return", "ret" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Asset.read
|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.
discord/asset.py
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): """|coro| Retrieves the content of this asset as a :class:`bytes` object. .. warning:: :class:`PartialEmoji` won't have a connection state if user created, and a URL won't be present if a custom image isn't associated with the asset, e.g. a guild with no custom icon. .. versionadded:: 1.1.0 Raises ------ DiscordException There was no valid URL or internal connection state. HTTPException Downloading the asset failed. NotFound The asset was deleted. Returns ------- :class:`bytes` The content of the asset. """ if not self._url: raise DiscordException('Invalid asset (no URL provided)') if self._state is None: raise DiscordException('Invalid state (no ConnectionState provided)') return await self._state.http.get_from_cdn(self._url)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/asset.py#L133-L166
[ "async", "def", "read", "(", "self", ")", ":", "if", "not", "self", ".", "_url", ":", "raise", "DiscordException", "(", "'Invalid asset (no URL provided)'", ")", "if", "self", ".", "_state", "is", "None", ":", "raise", "DiscordException", "(", "'Invalid state ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Asset.save
|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.
discord/asset.py
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): """|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)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/asset.py#L168-L198
[ "async", "def", "save", "(", "self", ",", "fp", ",", "*", ",", "seek_begin", "=", "True", ")", ":", "data", "=", "await", "self", ".", "read", "(", ")", "if", "isinstance", "(", "fp", ",", "io", ".", "IOBase", ")", "and", "fp", ".", "writable", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
DiscordWebSocket.from_client
Creates a main websocket for Discord from a :class:`Client`. This is for internal use only.
discord/gateway.py
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): """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
[ "Creates", "a", "main", "websocket", "for", "Discord", "from", "a", ":", "class", ":", "Client", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L219-L257
[ "async", "def", "from_client", "(", "cls", ",", "client", ",", "*", ",", "shard_id", "=", "None", ",", "session", "=", "None", ",", "sequence", "=", "None", ",", "resume", "=", "False", ")", ":", "gateway", "=", "await", "client", ".", "http", ".", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
DiscordWebSocket.wait_for
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.
discord/gateway.py
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): """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
[ "Waits", "for", "a", "DISPATCH", "d", "event", "that", "meets", "the", "predicate", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L259-L282
[ "def", "wait_for", "(", "self", ",", "event", ",", "predicate", ",", "result", "=", "None", ")", ":", "future", "=", "self", ".", "loop", ".", "create_future", "(", ")", "entry", "=", "EventListener", "(", "event", "=", "event", ",", "predicate", "=", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
DiscordWebSocket.identify
Sends the IDENTIFY packet.
discord/gateway.py
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): """Sends the IDENTIFY packet.""" payload = { 'op': self.IDENTIFY, 'd': { 'token': self.token, 'properties': { '$os': sys.platform, '$browser': 'discord.py', '$device': 'discord.py', '$referrer': '', '$referring_domain': '' }, 'compress': True, 'large_threshold': 250, 'v': 3 } } if not self._connection.is_bot: payload['d']['synced_guilds'] = [] if self.shard_id is not None and self.shard_count is not None: payload['d']['shard'] = [self.shard_id, self.shard_count] state = self._connection if state._activity is not None or state._status is not None: payload['d']['presence'] = { 'status': state._status, 'game': state._activity, 'since': 0, 'afk': False } await self.send_as_json(payload) log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)
[ "Sends", "the", "IDENTIFY", "packet", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L284-L319
[ "async", "def", "identify", "(", "self", ")", ":", "payload", "=", "{", "'op'", ":", "self", ".", "IDENTIFY", ",", "'d'", ":", "{", "'token'", ":", "self", ".", "token", ",", "'properties'", ":", "{", "'$os'", ":", "sys", ".", "platform", ",", "'$b...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
DiscordWebSocket.resume
Sends the RESUME packet.
discord/gateway.py
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): """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)
[ "Sends", "the", "RESUME", "packet", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L321-L333
[ "async", "def", "resume", "(", "self", ")", ":", "payload", "=", "{", "'op'", ":", "self", ".", "RESUME", ",", "'d'", ":", "{", "'seq'", ":", "self", ".", "sequence", ",", "'session_id'", ":", "self", ".", "session_id", ",", "'token'", ":", "self", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
DiscordWebSocket.poll_event
Polls for a DISPATCH event and handles the general gateway loop. Raises ------ ConnectionClosed The websocket connection was terminated for unhandled reasons.
discord/gateway.py
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): """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
[ "Polls", "for", "a", "DISPATCH", "event", "and", "handles", "the", "general", "gateway", "loop", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L460-L477
[ "async", "def", "poll_event", "(", "self", ")", ":", "try", ":", "msg", "=", "await", "self", ".", "recv", "(", ")", "await", "self", ".", "received_message", "(", "msg", ")", "except", "websockets", ".", "exceptions", ".", "ConnectionClosed", "as", "exc...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
DiscordVoiceWebSocket.from_client
Creates a voice websocket for the :class:`VoiceClient`.
discord/gateway.py
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): """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
[ "Creates", "a", "voice", "websocket", "for", "the", ":", "class", ":", "VoiceClient", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L625-L638
[ "async", "def", "from_client", "(", "cls", ",", "client", ",", "*", ",", "resume", "=", "False", ")", ":", "gateway", "=", "'wss://'", "+", "client", ".", "endpoint", "+", "'/?v=4'", "ws", "=", "await", "websockets", ".", "connect", "(", "gateway", ","...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Paginator.clear
Clears the paginator to have no pages.
discord/ext/commands/help.py
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): """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 = []
[ "Clears", "the", "paginator", "to", "have", "no", "pages", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L89-L97
[ "def", "clear", "(", "self", ")", ":", "if", "self", ".", "prefix", "is", "not", "None", ":", "self", ".", "_current_page", "=", "[", "self", ".", "prefix", "]", "self", ".", "_count", "=", "len", "(", "self", ".", "prefix", ")", "+", "1", "# pre...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Paginator.add_line
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`.
discord/ext/commands/help.py
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): """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
[ "Adds", "a", "line", "to", "the", "current", "page", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L103-L133
[ "def", "add_line", "(", "self", ",", "line", "=", "''", ",", "*", ",", "empty", "=", "False", ")", ":", "max_page_size", "=", "self", ".", "max_size", "-", "self", ".", "_prefix_len", "-", "2", "if", "len", "(", "line", ")", ">", "max_page_size", "...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Paginator.close_page
Prematurely terminate a page.
discord/ext/commands/help.py
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): """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
[ "Prematurely", "terminate", "a", "page", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L135-L146
[ "def", "close_page", "(", "self", ")", ":", "if", "self", ".", "suffix", "is", "not", "None", ":", "self", ".", "_current_page", ".", "append", "(", "self", ".", "suffix", ")", "self", ".", "_pages", ".", "append", "(", "'\\n'", ".", "join", "(", "...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
HelpCommand.get_bot_mapping
Retrieves the bot mapping passed to :meth:`send_bot_help`.
discord/ext/commands/help.py
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): """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
[ "Retrieves", "the", "bot", "mapping", "passed", "to", ":", "meth", ":", "send_bot_help", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L325-L333
[ "def", "get_bot_mapping", "(", "self", ")", ":", "bot", "=", "self", ".", "context", ".", "bot", "mapping", "=", "{", "cog", ":", "cog", ".", "get_commands", "(", ")", "for", "cog", "in", "bot", ".", "cogs", ".", "values", "(", ")", "}", "mapping",...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
HelpCommand.clean_prefix
The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
discord/ext/commands/help.py
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): """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)
[ "The", "cleaned", "up", "invoke", "prefix", ".", "i", ".", "e", ".", "mentions", "are" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L336-L343
[ "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 b...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
HelpCommand.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.
discord/ext/commands/help.py
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): """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
[ "Similar", "to", ":", "attr", ":", "Context", ".", "invoked_with", "except", "properly", "handles", "the", "case", "where", ":", "meth", ":", "Context", ".", "send_help", "is", "used", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L346-L364
[ "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", ".", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
HelpCommand.get_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.
discord/ext/commands/help.py
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): """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)
[ "Retrieves", "the", "signature", "portion", "of", "the", "help", "page", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L366-L390
[ "def", "get_command_signature", "(", "self", ",", "command", ")", ":", "parent", "=", "command", ".", "full_parent_name", "if", "len", "(", "command", ".", "aliases", ")", ">", "0", ":", "aliases", "=", "'|'", ".", "join", "(", "command", ".", "aliases",...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
HelpCommand.remove_mentions
Removes mentions from the string to prevent abuse. This includes ``@everyone``, ``@here``, member mentions and role mentions.
discord/ext/commands/help.py
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): """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)
[ "Removes", "mentions", "from", "the", "string", "to", "prevent", "abuse", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L392-L401
[ "def", "remove_mentions", "(", "self", ",", "string", ")", ":", "def", "replace", "(", "obj", ",", "*", ",", "transforms", "=", "self", ".", "MENTION_TRANSFORMS", ")", ":", "return", "transforms", ".", "get", "(", "obj", ".", "group", "(", "0", ")", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
HelpCommand.subcommand_not_found
|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.
discord/ext/commands/help.py
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): """|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)
[ "|maybecoro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L450-L478
[ "def", "subcommand_not_found", "(", "self", ",", "command", ",", "string", ")", ":", "if", "isinstance", "(", "command", ",", "Group", ")", "and", "len", "(", "command", ".", "all_commands", ")", ">", "0", ":", "return", "'Command \"{0.qualified_name}\" has no...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
HelpCommand.filter_commands
|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.
discord/ext/commands/help.py
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): """|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
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L480-L530
[ "async", "def", "filter_commands", "(", "self", ",", "commands", ",", "*", ",", "sort", "=", "False", ",", "key", "=", "None", ")", ":", "if", "sort", "and", "key", "is", "None", ":", "key", "=", "lambda", "c", ":", "c", ".", "name", "iterator", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
HelpCommand.get_max_size
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.
discord/ext/commands/help.py
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): """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)
[ "Returns", "the", "largest", "name", "length", "of", "the", "specified", "command", "list", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L532-L550
[ "def", "get_max_size", "(", "self", ",", "commands", ")", ":", "as_lengths", "=", "(", "discord", ".", "utils", ".", "_string_width", "(", "c", ".", "name", ")", "for", "c", "in", "commands", ")", "return", "max", "(", "as_lengths", ",", "default", "="...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
HelpCommand.command_callback
|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`
discord/ext/commands/help.py
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): """|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)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L754-L812
[ "async", "def", "command_callback", "(", "self", ",", "ctx", ",", "*", ",", "command", "=", "None", ")", ":", "await", "self", ".", "prepare_help_command", "(", "ctx", ",", "command", ")", "bot", "=", "ctx", ".", "bot", "if", "command", "is", "None", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
DefaultHelpCommand.shorten_text
Shortens text to fit into the :attr:`width`.
discord/ext/commands/help.py
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): """Shortens text to fit into the :attr:`width`.""" if len(text) > self.width: return text[:self.width - 3] + '...' return text
[ "Shortens", "text", "to", "fit", "into", "the", ":", "attr", ":", "width", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L865-L869
[ "def", "shorten_text", "(", "self", ",", "text", ")", ":", "if", "len", "(", "text", ")", ">", "self", ".", "width", ":", "return", "text", "[", ":", "self", ".", "width", "-", "3", "]", "+", "'...'", "return", "text" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
DefaultHelpCommand.add_indented_commands
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.
discord/ext/commands/help.py
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): """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))
[ "Indents", "a", "list", "of", "commands", "after", "the", "specified", "heading", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L877-L911
[ "def", "add_indented_commands", "(", "self", ",", "commands", ",", "*", ",", "heading", ",", "max_size", "=", "None", ")", ":", "if", "not", "commands", ":", "return", "self", ".", "paginator", ".", "add_line", "(", "heading", ")", "max_size", "=", "max_...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
DefaultHelpCommand.send_pages
A helper utility to send the page output from :attr:`paginator` to the destination.
discord/ext/commands/help.py
async def send_pages(self): """A helper utility to send the page output from :attr:`paginator` to the destination.""" destination = self.get_destination() for page in self.paginator.pages: await destination.send(page)
async def send_pages(self): """A helper utility to send the page output from :attr:`paginator` to the destination.""" destination = self.get_destination() for page in self.paginator.pages: await destination.send(page)
[ "A", "helper", "utility", "to", "send", "the", "page", "output", "from", ":", "attr", ":", "paginator", "to", "the", "destination", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L913-L917
[ "async", "def", "send_pages", "(", "self", ")", ":", "destination", "=", "self", ".", "get_destination", "(", ")", "for", "page", "in", "self", ".", "paginator", ".", "pages", ":", "await", "destination", ".", "send", "(", "page", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
MinimalHelpCommand.add_bot_commands_formatting
Adds the minified bot heading with commands to the output. The formatting should be added to the :attr:`paginator`. The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line. Parameters ----------- commands: Sequence[:class:`Command`] A list of commands that belong to the heading. heading: :class:`str` The heading to add to the line.
discord/ext/commands/help.py
def add_bot_commands_formatting(self, commands, heading): """Adds the minified bot heading with commands to the output. The formatting should be added to the :attr:`paginator`. The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line. Parameters ----------- commands: Sequence[:class:`Command`] A list of commands that belong to the heading. heading: :class:`str` The heading to add to the line. """ if commands: # U+2002 Middle Dot joined = '\u2002'.join(c.name for c in commands) self.paginator.add_line('__**%s**__' % heading) self.paginator.add_line(joined)
def add_bot_commands_formatting(self, commands, heading): """Adds the minified bot heading with commands to the output. The formatting should be added to the :attr:`paginator`. The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line. Parameters ----------- commands: Sequence[:class:`Command`] A list of commands that belong to the heading. heading: :class:`str` The heading to add to the line. """ if commands: # U+2002 Middle Dot joined = '\u2002'.join(c.name for c in commands) self.paginator.add_line('__**%s**__' % heading) self.paginator.add_line(joined)
[ "Adds", "the", "minified", "bot", "heading", "with", "commands", "to", "the", "output", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L1092-L1111
[ "def", "add_bot_commands_formatting", "(", "self", ",", "commands", ",", "heading", ")", ":", "if", "commands", ":", "# U+2002 Middle Dot", "joined", "=", "'\\u2002'", ".", "join", "(", "c", ".", "name", "for", "c", "in", "commands", ")", "self", ".", "pag...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
MinimalHelpCommand.add_subcommand_formatting
Adds formatting information on a subcommand. The formatting should be added to the :attr:`paginator`. The default implementation is the prefix and the :attr:`Command.qualified_name` optionally followed by an En dash and the command's :attr:`Command.short_doc`. Parameters ----------- command: :class:`Command` The command to show information of.
discord/ext/commands/help.py
def add_subcommand_formatting(self, command): """Adds formatting information on a subcommand. The formatting should be added to the :attr:`paginator`. The default implementation is the prefix and the :attr:`Command.qualified_name` optionally followed by an En dash and the command's :attr:`Command.short_doc`. Parameters ----------- command: :class:`Command` The command to show information of. """ fmt = '{0}{1} \N{EN DASH} {2}' if command.short_doc else '{0}{1}' self.paginator.add_line(fmt.format(self.clean_prefix, command.qualified_name, command.short_doc))
def add_subcommand_formatting(self, command): """Adds formatting information on a subcommand. The formatting should be added to the :attr:`paginator`. The default implementation is the prefix and the :attr:`Command.qualified_name` optionally followed by an En dash and the command's :attr:`Command.short_doc`. Parameters ----------- command: :class:`Command` The command to show information of. """ fmt = '{0}{1} \N{EN DASH} {2}' if command.short_doc else '{0}{1}' self.paginator.add_line(fmt.format(self.clean_prefix, command.qualified_name, command.short_doc))
[ "Adds", "formatting", "information", "on", "a", "subcommand", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L1113-L1127
[ "def", "add_subcommand_formatting", "(", "self", ",", "command", ")", ":", "fmt", "=", "'{0}{1} \\N{EN DASH} {2}'", "if", "command", ".", "short_doc", "else", "'{0}{1}'", "self", ".", "paginator", ".", "add_line", "(", "fmt", ".", "format", "(", "self", ".", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
MinimalHelpCommand.add_aliases_formatting
Adds the formatting information on a command's aliases. The formatting should be added to the :attr:`paginator`. The default implementation is the :attr:`aliases_heading` bolded followed by a comma separated list of aliases. This is not called if there are no aliases to format. Parameters ----------- aliases: Sequence[:class:`str`] A list of aliases to format.
discord/ext/commands/help.py
def add_aliases_formatting(self, aliases): """Adds the formatting information on a command's aliases. The formatting should be added to the :attr:`paginator`. The default implementation is the :attr:`aliases_heading` bolded followed by a comma separated list of aliases. This is not called if there are no aliases to format. Parameters ----------- aliases: Sequence[:class:`str`] A list of aliases to format. """ self.paginator.add_line('**%s** %s' % (self.aliases_heading, ', '.join(aliases)), empty=True)
def add_aliases_formatting(self, aliases): """Adds the formatting information on a command's aliases. The formatting should be added to the :attr:`paginator`. The default implementation is the :attr:`aliases_heading` bolded followed by a comma separated list of aliases. This is not called if there are no aliases to format. Parameters ----------- aliases: Sequence[:class:`str`] A list of aliases to format. """ self.paginator.add_line('**%s** %s' % (self.aliases_heading, ', '.join(aliases)), empty=True)
[ "Adds", "the", "formatting", "information", "on", "a", "command", "s", "aliases", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L1129-L1144
[ "def", "add_aliases_formatting", "(", "self", ",", "aliases", ")", ":", "self", ".", "paginator", ".", "add_line", "(", "'**%s** %s'", "%", "(", "self", ".", "aliases_heading", ",", "', '", ".", "join", "(", "aliases", ")", ")", ",", "empty", "=", "True"...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
MinimalHelpCommand.add_command_formatting
A utility function to format commands and groups. Parameters ------------ command: :class:`Command` The command to format.
discord/ext/commands/help.py
def add_command_formatting(self, command): """A utility function to format commands and groups. Parameters ------------ command: :class:`Command` The command to format. """ if command.description: self.paginator.add_line(command.description, empty=True) signature = self.get_command_signature(command) if command.aliases: self.paginator.add_line(signature) self.add_aliases_formatting(command.aliases) else: self.paginator.add_line(signature, empty=True) if command.help: try: self.paginator.add_line(command.help, empty=True) except RuntimeError: for line in command.help.splitlines(): self.paginator.add_line(line) self.paginator.add_line()
def add_command_formatting(self, command): """A utility function to format commands and groups. Parameters ------------ command: :class:`Command` The command to format. """ if command.description: self.paginator.add_line(command.description, empty=True) signature = self.get_command_signature(command) if command.aliases: self.paginator.add_line(signature) self.add_aliases_formatting(command.aliases) else: self.paginator.add_line(signature, empty=True) if command.help: try: self.paginator.add_line(command.help, empty=True) except RuntimeError: for line in command.help.splitlines(): self.paginator.add_line(line) self.paginator.add_line()
[ "A", "utility", "function", "to", "format", "commands", "and", "groups", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L1146-L1171
[ "def", "add_command_formatting", "(", "self", ",", "command", ")", ":", "if", "command", ".", "description", ":", "self", ".", "paginator", ".", "add_line", "(", "command", ".", "description", ",", "empty", "=", "True", ")", "signature", "=", "self", ".", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
VoiceClient.disconnect
|coro| Disconnects this voice client from voice.
discord/voice_client.py
async def disconnect(self, *, force=False): """|coro| Disconnects this voice client from voice. """ if not force and not self.is_connected(): return self.stop() self._connected.clear() try: if self.ws: await self.ws.close() await self.terminate_handshake(remove=True) finally: if self.socket: self.socket.close()
async def disconnect(self, *, force=False): """|coro| Disconnects this voice client from voice. """ if not force and not self.is_connected(): return self.stop() self._connected.clear() try: if self.ws: await self.ws.close() await self.terminate_handshake(remove=True) finally: if self.socket: self.socket.close()
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/voice_client.py#L269-L287
[ "async", "def", "disconnect", "(", "self", ",", "*", ",", "force", "=", "False", ")", ":", "if", "not", "force", "and", "not", "self", ".", "is_connected", "(", ")", ":", "return", "self", ".", "stop", "(", ")", "self", ".", "_connected", ".", "cle...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
VoiceClient.move_to
|coro| Moves you to a different voice channel. Parameters ----------- channel: :class:`abc.Snowflake` The channel to move to. Must be a voice channel.
discord/voice_client.py
async def move_to(self, channel): """|coro| Moves you to a different voice channel. Parameters ----------- channel: :class:`abc.Snowflake` The channel to move to. Must be a voice channel. """ guild_id, _ = self.channel._get_voice_state_pair() await self.main_ws.voice_state(guild_id, channel.id)
async def move_to(self, channel): """|coro| Moves you to a different voice channel. Parameters ----------- channel: :class:`abc.Snowflake` The channel to move to. Must be a voice channel. """ guild_id, _ = self.channel._get_voice_state_pair() await self.main_ws.voice_state(guild_id, channel.id)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/voice_client.py#L289-L300
[ "async", "def", "move_to", "(", "self", ",", "channel", ")", ":", "guild_id", ",", "_", "=", "self", ".", "channel", ".", "_get_voice_state_pair", "(", ")", "await", "self", ".", "main_ws", ".", "voice_state", "(", "guild_id", ",", "channel", ".", "id", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
VoiceClient.play
Plays an :class:`AudioSource`. The finalizer, ``after`` is called after the source has been exhausted or an error occurred. If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. Parameters ----------- source: :class:`AudioSource` The audio source we're reading from. after The finalizer that is called after the stream is exhausted. All exceptions it throws are silently discarded. This function must have a single parameter, ``error``, that denotes an optional exception that was raised during playing. Raises ------- ClientException Already playing audio or not connected. TypeError source is not a :class:`AudioSource` or after is not a callable.
discord/voice_client.py
def play(self, source, *, after=None): """Plays an :class:`AudioSource`. The finalizer, ``after`` is called after the source has been exhausted or an error occurred. If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. Parameters ----------- source: :class:`AudioSource` The audio source we're reading from. after The finalizer that is called after the stream is exhausted. All exceptions it throws are silently discarded. This function must have a single parameter, ``error``, that denotes an optional exception that was raised during playing. Raises ------- ClientException Already playing audio or not connected. TypeError source is not a :class:`AudioSource` or after is not a callable. """ if not self.is_connected(): raise ClientException('Not connected to voice.') if self.is_playing(): raise ClientException('Already playing audio.') if not isinstance(source, AudioSource): raise TypeError('source must an AudioSource not {0.__class__.__name__}'.format(source)) self._player = AudioPlayer(source, self, after=after) self._player.start()
def play(self, source, *, after=None): """Plays an :class:`AudioSource`. The finalizer, ``after`` is called after the source has been exhausted or an error occurred. If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. Parameters ----------- source: :class:`AudioSource` The audio source we're reading from. after The finalizer that is called after the stream is exhausted. All exceptions it throws are silently discarded. This function must have a single parameter, ``error``, that denotes an optional exception that was raised during playing. Raises ------- ClientException Already playing audio or not connected. TypeError source is not a :class:`AudioSource` or after is not a callable. """ if not self.is_connected(): raise ClientException('Not connected to voice.') if self.is_playing(): raise ClientException('Already playing audio.') if not isinstance(source, AudioSource): raise TypeError('source must an AudioSource not {0.__class__.__name__}'.format(source)) self._player = AudioPlayer(source, self, after=after) self._player.start()
[ "Plays", "an", ":", "class", ":", "AudioSource", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/voice_client.py#L334-L371
[ "def", "play", "(", "self", ",", "source", ",", "*", ",", "after", "=", "None", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "raise", "ClientException", "(", "'Not connected to voice.'", ")", "if", "self", ".", "is_playing", "(", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
VoiceClient.send_audio_packet
Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: bytes The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: bool Indicates if ``data`` should be encoded into Opus. Raises ------- ClientException You are not connected. OpusError Encoding the data failed.
discord/voice_client.py
def send_audio_packet(self, data, *, encode=True): """Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: bytes The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: bool Indicates if ``data`` should be encoded into Opus. Raises ------- ClientException You are not connected. OpusError Encoding the data failed. """ self.checked_add('sequence', 1, 65535) if encode: encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME) else: encoded_data = data packet = self._get_voice_packet(encoded_data) try: self.socket.sendto(packet, (self.endpoint_ip, self.voice_port)) except BlockingIOError: log.warning('A packet has been dropped (seq: %s, timestamp: %s)', self.sequence, self.timestamp) self.checked_add('timestamp', self.encoder.SAMPLES_PER_FRAME, 4294967295)
def send_audio_packet(self, data, *, encode=True): """Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: bytes The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: bool Indicates if ``data`` should be encoded into Opus. Raises ------- ClientException You are not connected. OpusError Encoding the data failed. """ self.checked_add('sequence', 1, 65535) if encode: encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME) else: encoded_data = data packet = self._get_voice_packet(encoded_data) try: self.socket.sendto(packet, (self.endpoint_ip, self.voice_port)) except BlockingIOError: log.warning('A packet has been dropped (seq: %s, timestamp: %s)', self.sequence, self.timestamp) self.checked_add('timestamp', self.encoder.SAMPLES_PER_FRAME, 4294967295)
[ "Sends", "an", "audio", "packet", "composed", "of", "the", "data", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/voice_client.py#L415-L446
[ "def", "send_audio_packet", "(", "self", ",", "data", ",", "*", ",", "encode", "=", "True", ")", ":", "self", ".", "checked_add", "(", "'sequence'", ",", "1", ",", "65535", ")", "if", "encode", ":", "encoded_data", "=", "self", ".", "encoder", ".", "...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.on_error
|coro| The default error handler provided by the client. By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. Check :func:`discord.on_error` for more details.
discord/client.py
async def on_error(self, event_method, *args, **kwargs): """|coro| The default error handler provided by the client. By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. Check :func:`discord.on_error` for more details. """ print('Ignoring exception in {}'.format(event_method), file=sys.stderr) traceback.print_exc()
async def on_error(self, event_method, *args, **kwargs): """|coro| The default error handler provided by the client. By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. Check :func:`discord.on_error` for more details. """ print('Ignoring exception in {}'.format(event_method), file=sys.stderr) traceback.print_exc()
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L300-L310
[ "async", "def", "on_error", "(", "self", ",", "event_method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "print", "(", "'Ignoring exception in {}'", ".", "format", "(", "event_method", ")", ",", "file", "=", "sys", ".", "stderr", ")", "tracebac...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.request_offline_members
r"""|coro| Requests previously offline members from the guild to be filled up into the :attr:`.Guild.members` cache. This function is usually not called. It should only be used if you have the ``fetch_offline_members`` parameter set to ``False``. When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if :attr:`.Guild.large` is ``True``. Parameters ----------- \*guilds: :class:`Guild` An argument list of guilds to request offline members for. Raises ------- InvalidArgument If any guild is unavailable or not large in the collection.
discord/client.py
async def request_offline_members(self, *guilds): r"""|coro| Requests previously offline members from the guild to be filled up into the :attr:`.Guild.members` cache. This function is usually not called. It should only be used if you have the ``fetch_offline_members`` parameter set to ``False``. When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if :attr:`.Guild.large` is ``True``. Parameters ----------- \*guilds: :class:`Guild` An argument list of guilds to request offline members for. Raises ------- InvalidArgument If any guild is unavailable or not large in the collection. """ if any(not g.large or g.unavailable for g in guilds): raise InvalidArgument('An unavailable or non-large guild was passed.') await self._connection.request_offline_members(guilds)
async def request_offline_members(self, *guilds): r"""|coro| Requests previously offline members from the guild to be filled up into the :attr:`.Guild.members` cache. This function is usually not called. It should only be used if you have the ``fetch_offline_members`` parameter set to ``False``. When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if :attr:`.Guild.large` is ``True``. Parameters ----------- \*guilds: :class:`Guild` An argument list of guilds to request offline members for. Raises ------- InvalidArgument If any guild is unavailable or not large in the collection. """ if any(not g.large or g.unavailable for g in guilds): raise InvalidArgument('An unavailable or non-large guild was passed.') await self._connection.request_offline_members(guilds)
[ "r", "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L312-L338
[ "async", "def", "request_offline_members", "(", "self", ",", "*", "guilds", ")", ":", "if", "any", "(", "not", "g", ".", "large", "or", "g", ".", "unavailable", "for", "g", "in", "guilds", ")", ":", "raise", "InvalidArgument", "(", "'An unavailable or non-...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.login
|coro| Logs in the client with the specified credentials. This function can be used in two different ways. .. warning:: Logging on with a user token is against the Discord `Terms of Service <https://support.discordapp.com/hc/en-us/articles/115002192352>`_ and doing so might potentially get your account banned. Use this at your own risk. Parameters ----------- token: :class:`str` The authentication token. Do not prefix this token with anything as the library will do it for you. bot: :class:`bool` Keyword argument that specifies if the account logging on is a bot token or not. Raises ------ LoginFailure The wrong credentials are passed. HTTPException An unknown HTTP related error occurred, usually when it isn't 200 or the known incorrect credentials passing status code.
discord/client.py
async def login(self, token, *, bot=True): """|coro| Logs in the client with the specified credentials. This function can be used in two different ways. .. warning:: Logging on with a user token is against the Discord `Terms of Service <https://support.discordapp.com/hc/en-us/articles/115002192352>`_ and doing so might potentially get your account banned. Use this at your own risk. Parameters ----------- token: :class:`str` The authentication token. Do not prefix this token with anything as the library will do it for you. bot: :class:`bool` Keyword argument that specifies if the account logging on is a bot token or not. Raises ------ LoginFailure The wrong credentials are passed. HTTPException An unknown HTTP related error occurred, usually when it isn't 200 or the known incorrect credentials passing status code. """ log.info('logging in using static token') await self.http.static_login(token, bot=bot) self._connection.is_bot = bot
async def login(self, token, *, bot=True): """|coro| Logs in the client with the specified credentials. This function can be used in two different ways. .. warning:: Logging on with a user token is against the Discord `Terms of Service <https://support.discordapp.com/hc/en-us/articles/115002192352>`_ and doing so might potentially get your account banned. Use this at your own risk. Parameters ----------- token: :class:`str` The authentication token. Do not prefix this token with anything as the library will do it for you. bot: :class:`bool` Keyword argument that specifies if the account logging on is a bot token or not. Raises ------ LoginFailure The wrong credentials are passed. HTTPException An unknown HTTP related error occurred, usually when it isn't 200 or the known incorrect credentials passing status code. """ log.info('logging in using static token') await self.http.static_login(token, bot=bot) self._connection.is_bot = bot
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L342-L377
[ "async", "def", "login", "(", "self", ",", "token", ",", "*", ",", "bot", "=", "True", ")", ":", "log", ".", "info", "(", "'logging in using static token'", ")", "await", "self", ".", "http", ".", "static_login", "(", "token", ",", "bot", "=", "bot", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.connect
|coro| Creates a websocket connection and lets the websocket listen to messages from discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated. Parameters ----------- reconnect: :class:`bool` If we should attempt reconnecting, either due to internet failure or a specific failure on Discord's part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens). Raises ------- GatewayNotFound If the gateway to connect to discord is not found. Usually if this is thrown then there is a discord API outage. ConnectionClosed The websocket connection has been terminated.
discord/client.py
async def connect(self, *, reconnect=True): """|coro| Creates a websocket connection and lets the websocket listen to messages from discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated. Parameters ----------- reconnect: :class:`bool` If we should attempt reconnecting, either due to internet failure or a specific failure on Discord's part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens). Raises ------- GatewayNotFound If the gateway to connect to discord is not found. Usually if this is thrown then there is a discord API outage. ConnectionClosed The websocket connection has been terminated. """ backoff = ExponentialBackoff() while not self.is_closed(): try: await self._connect() except (OSError, HTTPException, GatewayNotFound, ConnectionClosed, aiohttp.ClientError, asyncio.TimeoutError, websockets.InvalidHandshake, websockets.WebSocketProtocolError) as exc: self.dispatch('disconnect') if not reconnect: await self.close() if isinstance(exc, ConnectionClosed) and exc.code == 1000: # clean close, don't re-raise this return raise if self.is_closed(): return # We should only get this when an unhandled close code happens, # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc) # sometimes, discord sends us 1000 for unknown reasons so we should reconnect # regardless and rely on is_closed instead if isinstance(exc, ConnectionClosed): if exc.code != 1000: await self.close() raise retry = backoff.delay() log.exception("Attempting a reconnect in %.2fs", retry) await asyncio.sleep(retry, loop=self.loop)
async def connect(self, *, reconnect=True): """|coro| Creates a websocket connection and lets the websocket listen to messages from discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated. Parameters ----------- reconnect: :class:`bool` If we should attempt reconnecting, either due to internet failure or a specific failure on Discord's part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens). Raises ------- GatewayNotFound If the gateway to connect to discord is not found. Usually if this is thrown then there is a discord API outage. ConnectionClosed The websocket connection has been terminated. """ backoff = ExponentialBackoff() while not self.is_closed(): try: await self._connect() except (OSError, HTTPException, GatewayNotFound, ConnectionClosed, aiohttp.ClientError, asyncio.TimeoutError, websockets.InvalidHandshake, websockets.WebSocketProtocolError) as exc: self.dispatch('disconnect') if not reconnect: await self.close() if isinstance(exc, ConnectionClosed) and exc.code == 1000: # clean close, don't re-raise this return raise if self.is_closed(): return # We should only get this when an unhandled close code happens, # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc) # sometimes, discord sends us 1000 for unknown reasons so we should reconnect # regardless and rely on is_closed instead if isinstance(exc, ConnectionClosed): if exc.code != 1000: await self.close() raise retry = backoff.delay() log.exception("Attempting a reconnect in %.2fs", retry) await asyncio.sleep(retry, loop=self.loop)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L405-L465
[ "async", "def", "connect", "(", "self", ",", "*", ",", "reconnect", "=", "True", ")", ":", "backoff", "=", "ExponentialBackoff", "(", ")", "while", "not", "self", ".", "is_closed", "(", ")", ":", "try", ":", "await", "self", ".", "_connect", "(", ")"...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.close
|coro| Closes the connection to discord.
discord/client.py
async def close(self): """|coro| Closes the connection to discord. """ if self._closed: return await self.http.close() self._closed = True for voice in self.voice_clients: try: await voice.disconnect() except Exception: # if an error happens during disconnects, disregard it. pass if self.ws is not None and self.ws.open: await self.ws.close() self._ready.clear()
async def close(self): """|coro| Closes the connection to discord. """ if self._closed: return await self.http.close() self._closed = True for voice in self.voice_clients: try: await voice.disconnect() except Exception: # if an error happens during disconnects, disregard it. pass if self.ws is not None and self.ws.open: await self.ws.close() self._ready.clear()
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L467-L488
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "_closed", ":", "return", "await", "self", ".", "http", ".", "close", "(", ")", "self", ".", "_closed", "=", "True", "for", "voice", "in", "self", ".", "voice_clients", ":", "try", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.clear
Clears the internal state of the bot. After this, the bot can be considered "re-opened", i.e. :meth:`.is_closed` and :meth:`.is_ready` both return ``False`` along with the bot's internal cache cleared.
discord/client.py
def clear(self): """Clears the internal state of the bot. After this, the bot can be considered "re-opened", i.e. :meth:`.is_closed` and :meth:`.is_ready` both return ``False`` along with the bot's internal cache cleared. """ self._closed = False self._ready.clear() self._connection.clear() self.http.recreate()
def clear(self): """Clears the internal state of the bot. After this, the bot can be considered "re-opened", i.e. :meth:`.is_closed` and :meth:`.is_ready` both return ``False`` along with the bot's internal cache cleared. """ self._closed = False self._ready.clear() self._connection.clear() self.http.recreate()
[ "Clears", "the", "internal", "state", "of", "the", "bot", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L490-L500
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_closed", "=", "False", "self", ".", "_ready", ".", "clear", "(", ")", "self", ".", "_connection", ".", "clear", "(", ")", "self", ".", "http", ".", "recreate", "(", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.start
|coro| A shorthand coroutine for :meth:`login` + :meth:`connect`.
discord/client.py
async def start(self, *args, **kwargs): """|coro| A shorthand coroutine for :meth:`login` + :meth:`connect`. """ bot = kwargs.pop('bot', True) reconnect = kwargs.pop('reconnect', True) await self.login(*args, bot=bot) await self.connect(reconnect=reconnect)
async def start(self, *args, **kwargs): """|coro| A shorthand coroutine for :meth:`login` + :meth:`connect`. """ bot = kwargs.pop('bot', True) reconnect = kwargs.pop('reconnect', True) await self.login(*args, bot=bot) await self.connect(reconnect=reconnect)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L502-L511
[ "async", "def", "start", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "bot", "=", "kwargs", ".", "pop", "(", "'bot'", ",", "True", ")", "reconnect", "=", "kwargs", ".", "pop", "(", "'reconnect'", ",", "True", ")", "await", "s...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.run
A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then this function should not be used. Use :meth:`start` coroutine or :meth:`connect` + :meth:`login`. Roughly Equivalent to: :: try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(logout()) # cancel all tasks lingering finally: loop.close() .. warning:: This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
discord/client.py
def run(self, *args, **kwargs): """A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then this function should not be used. Use :meth:`start` coroutine or :meth:`connect` + :meth:`login`. Roughly Equivalent to: :: try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(logout()) # cancel all tasks lingering finally: loop.close() .. warning:: This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns. """ async def runner(): try: await self.start(*args, **kwargs) finally: await self.close() try: self.loop.run_until_complete(runner()) except KeyboardInterrupt: log.info('Received signal to terminate bot and event loop.') finally: log.info('Cleaning up tasks.') _cleanup_loop(self.loop)
def run(self, *args, **kwargs): """A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then this function should not be used. Use :meth:`start` coroutine or :meth:`connect` + :meth:`login`. Roughly Equivalent to: :: try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(logout()) # cancel all tasks lingering finally: loop.close() .. warning:: This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns. """ async def runner(): try: await self.start(*args, **kwargs) finally: await self.close() try: self.loop.run_until_complete(runner()) except KeyboardInterrupt: log.info('Received signal to terminate bot and event loop.') finally: log.info('Cleaning up tasks.') _cleanup_loop(self.loop)
[ "A", "blocking", "call", "that", "abstracts", "away", "the", "event", "loop", "initialisation", "from", "you", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L513-L549
[ "def", "run", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "async", "def", "runner", "(", ")", ":", "try", ":", "await", "self", ".", "start", "(", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "await", "self",...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.wait_for
|coro| Waits for a WebSocket event to be dispatched. This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way. The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default, it does not timeout. Note that this does propagate the :exc:`asyncio.TimeoutError` for you in case of timeout and is provided for ease of use. In case the event returns multiple arguments, a :class:`tuple` containing those arguments is returned instead. Please check the :ref:`documentation <discord-api-events>` for a list of events and their parameters. This function returns the **first event that meets the requirements**. Examples --------- Waiting for a user reply: :: @client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send('Hello {.author}!'.format(msg)) Waiting for a thumbs up reaction from the message author: :: @client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that \N{THUMBS UP SIGN} reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('\N{THUMBS DOWN SIGN}') else: await channel.send('\N{THUMBS UP SIGN}') Parameters ------------ event: :class:`str` The event name, similar to the :ref:`event reference <discord-api-events>`, but without the ``on_`` prefix, to wait for. check: Optional[predicate] A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for. timeout: Optional[:class:`float`] The number of seconds to wait before timing out and raising :exc:`asyncio.TimeoutError`. Raises ------- asyncio.TimeoutError If a timeout is provided and it was reached. Returns -------- Any Returns no arguments, a single argument, or a :class:`tuple` of multiple arguments that mirrors the parameters passed in the :ref:`event reference <discord-api-events>`.
discord/client.py
def wait_for(self, event, *, check=None, timeout=None): """|coro| Waits for a WebSocket event to be dispatched. This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way. The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default, it does not timeout. Note that this does propagate the :exc:`asyncio.TimeoutError` for you in case of timeout and is provided for ease of use. In case the event returns multiple arguments, a :class:`tuple` containing those arguments is returned instead. Please check the :ref:`documentation <discord-api-events>` for a list of events and their parameters. This function returns the **first event that meets the requirements**. Examples --------- Waiting for a user reply: :: @client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send('Hello {.author}!'.format(msg)) Waiting for a thumbs up reaction from the message author: :: @client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that \N{THUMBS UP SIGN} reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('\N{THUMBS DOWN SIGN}') else: await channel.send('\N{THUMBS UP SIGN}') Parameters ------------ event: :class:`str` The event name, similar to the :ref:`event reference <discord-api-events>`, but without the ``on_`` prefix, to wait for. check: Optional[predicate] A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for. timeout: Optional[:class:`float`] The number of seconds to wait before timing out and raising :exc:`asyncio.TimeoutError`. Raises ------- asyncio.TimeoutError If a timeout is provided and it was reached. Returns -------- Any Returns no arguments, a single argument, or a :class:`tuple` of multiple arguments that mirrors the parameters passed in the :ref:`event reference <discord-api-events>`. """ future = self.loop.create_future() if check is None: def _check(*args): return True check = _check ev = event.lower() try: listeners = self._listeners[ev] except KeyError: listeners = [] self._listeners[ev] = listeners listeners.append((future, check)) return asyncio.wait_for(future, timeout, loop=self.loop)
def wait_for(self, event, *, check=None, timeout=None): """|coro| Waits for a WebSocket event to be dispatched. This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way. The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default, it does not timeout. Note that this does propagate the :exc:`asyncio.TimeoutError` for you in case of timeout and is provided for ease of use. In case the event returns multiple arguments, a :class:`tuple` containing those arguments is returned instead. Please check the :ref:`documentation <discord-api-events>` for a list of events and their parameters. This function returns the **first event that meets the requirements**. Examples --------- Waiting for a user reply: :: @client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send('Hello {.author}!'.format(msg)) Waiting for a thumbs up reaction from the message author: :: @client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that \N{THUMBS UP SIGN} reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('\N{THUMBS DOWN SIGN}') else: await channel.send('\N{THUMBS UP SIGN}') Parameters ------------ event: :class:`str` The event name, similar to the :ref:`event reference <discord-api-events>`, but without the ``on_`` prefix, to wait for. check: Optional[predicate] A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for. timeout: Optional[:class:`float`] The number of seconds to wait before timing out and raising :exc:`asyncio.TimeoutError`. Raises ------- asyncio.TimeoutError If a timeout is provided and it was reached. Returns -------- Any Returns no arguments, a single argument, or a :class:`tuple` of multiple arguments that mirrors the parameters passed in the :ref:`event reference <discord-api-events>`. """ future = self.loop.create_future() if check is None: def _check(*args): return True check = _check ev = event.lower() try: listeners = self._listeners[ev] except KeyError: listeners = [] self._listeners[ev] = listeners listeners.append((future, check)) return asyncio.wait_for(future, timeout, loop=self.loop)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L640-L736
[ "def", "wait_for", "(", "self", ",", "event", ",", "*", ",", "check", "=", "None", ",", "timeout", "=", "None", ")", ":", "future", "=", "self", ".", "loop", ".", "create_future", "(", ")", "if", "check", "is", "None", ":", "def", "_check", "(", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.event
A decorator that registers an event to listen to. You can find more info about the events on the :ref:`documentation below <discord-api-events>`. The events must be a |corourl|_, if not, :exc:`TypeError` is raised. Example --------- .. code-block:: python3 @client.event async def on_ready(): print('Ready!') Raises -------- TypeError The coroutine passed is not actually a coroutine.
discord/client.py
def event(self, coro): """A decorator that registers an event to listen to. You can find more info about the events on the :ref:`documentation below <discord-api-events>`. The events must be a |corourl|_, if not, :exc:`TypeError` is raised. Example --------- .. code-block:: python3 @client.event async def on_ready(): print('Ready!') Raises -------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('event registered must be a coroutine function') setattr(self, coro.__name__, coro) log.debug('%s has successfully been registered as an event', coro.__name__) return coro
def event(self, coro): """A decorator that registers an event to listen to. You can find more info about the events on the :ref:`documentation below <discord-api-events>`. The events must be a |corourl|_, if not, :exc:`TypeError` is raised. Example --------- .. code-block:: python3 @client.event async def on_ready(): print('Ready!') Raises -------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('event registered must be a coroutine function') setattr(self, coro.__name__, coro) log.debug('%s has successfully been registered as an event', coro.__name__) return coro
[ "A", "decorator", "that", "registers", "an", "event", "to", "listen", "to", "." ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L740-L767
[ "def", "event", "(", "self", ",", "coro", ")", ":", "if", "not", "asyncio", ".", "iscoroutinefunction", "(", "coro", ")", ":", "raise", "TypeError", "(", "'event registered must be a coroutine function'", ")", "setattr", "(", "self", ",", "coro", ".", "__name_...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.change_presence
|coro| Changes the client's presence. The activity parameter is a :class:`.Activity` object (not a string) that represents the activity being done currently. This could also be the slimmed down versions, :class:`.Game` and :class:`.Streaming`. Example --------- .. code-block:: python3 game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) Parameters ---------- activity: Optional[Union[:class:`.Game`, :class:`.Streaming`, :class:`.Activity`]] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`.Status`] Indicates what status to change to. If None, then :attr:`.Status.online` is used. afk: :class:`bool` Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying. Raises ------ InvalidArgument If the ``activity`` parameter is not the proper type.
discord/client.py
async def change_presence(self, *, activity=None, status=None, afk=False): """|coro| Changes the client's presence. The activity parameter is a :class:`.Activity` object (not a string) that represents the activity being done currently. This could also be the slimmed down versions, :class:`.Game` and :class:`.Streaming`. Example --------- .. code-block:: python3 game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) Parameters ---------- activity: Optional[Union[:class:`.Game`, :class:`.Streaming`, :class:`.Activity`]] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`.Status`] Indicates what status to change to. If None, then :attr:`.Status.online` is used. afk: :class:`bool` Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying. Raises ------ InvalidArgument If the ``activity`` parameter is not the proper type. """ if status is None: status = 'online' status_enum = Status.online elif status is Status.offline: status = 'invisible' status_enum = Status.offline else: status_enum = status status = str(status) await self.ws.change_presence(activity=activity, status=status, afk=afk) for guild in self._connection.guilds: me = guild.me if me is None: continue me.activities = (activity,) me.status = status_enum
async def change_presence(self, *, activity=None, status=None, afk=False): """|coro| Changes the client's presence. The activity parameter is a :class:`.Activity` object (not a string) that represents the activity being done currently. This could also be the slimmed down versions, :class:`.Game` and :class:`.Streaming`. Example --------- .. code-block:: python3 game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) Parameters ---------- activity: Optional[Union[:class:`.Game`, :class:`.Streaming`, :class:`.Activity`]] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`.Status`] Indicates what status to change to. If None, then :attr:`.Status.online` is used. afk: :class:`bool` Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying. Raises ------ InvalidArgument If the ``activity`` parameter is not the proper type. """ if status is None: status = 'online' status_enum = Status.online elif status is Status.offline: status = 'invisible' status_enum = Status.offline else: status_enum = status status = str(status) await self.ws.change_presence(activity=activity, status=status, afk=afk) for guild in self._connection.guilds: me = guild.me if me is None: continue me.activities = (activity,) me.status = status_enum
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L769-L822
[ "async", "def", "change_presence", "(", "self", ",", "*", ",", "activity", "=", "None", ",", "status", "=", "None", ",", "afk", "=", "False", ")", ":", "if", "status", "is", "None", ":", "status", "=", "'online'", "status_enum", "=", "Status", ".", "...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.fetch_guilds
|coro| Retrieves an :class:`.AsyncIterator` that enables receiving your guilds. .. note:: Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`, :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`. .. note:: This method is an API call. For general usage, consider :attr:`guilds` instead. All parameters are optional. Parameters ----------- limit: Optional[:class:`int`] The number of guilds to retrieve. If ``None``, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to 100. before: :class:`.abc.Snowflake` or :class:`datetime.datetime` Retrieves guilds before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time. after: :class:`.abc.Snowflake` or :class:`datetime.datetime` Retrieve guilds after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time. Raises ------ HTTPException Getting the guilds failed. Yields -------- :class:`.Guild` The guild with the guild data parsed. Examples --------- Usage :: async for guild in client.fetch_guilds(limit=150): print(guild.name) Flattening into a list :: guilds = await client.fetch_guilds(limit=150).flatten() # guilds is now a list of Guild...
discord/client.py
def fetch_guilds(self, *, limit=100, before=None, after=None): """|coro| Retrieves an :class:`.AsyncIterator` that enables receiving your guilds. .. note:: Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`, :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`. .. note:: This method is an API call. For general usage, consider :attr:`guilds` instead. All parameters are optional. Parameters ----------- limit: Optional[:class:`int`] The number of guilds to retrieve. If ``None``, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to 100. before: :class:`.abc.Snowflake` or :class:`datetime.datetime` Retrieves guilds before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time. after: :class:`.abc.Snowflake` or :class:`datetime.datetime` Retrieve guilds after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time. Raises ------ HTTPException Getting the guilds failed. Yields -------- :class:`.Guild` The guild with the guild data parsed. Examples --------- Usage :: async for guild in client.fetch_guilds(limit=150): print(guild.name) Flattening into a list :: guilds = await client.fetch_guilds(limit=150).flatten() # guilds is now a list of Guild... """ return GuildIterator(self, limit=limit, before=before, after=after)
def fetch_guilds(self, *, limit=100, before=None, after=None): """|coro| Retrieves an :class:`.AsyncIterator` that enables receiving your guilds. .. note:: Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`, :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`. .. note:: This method is an API call. For general usage, consider :attr:`guilds` instead. All parameters are optional. Parameters ----------- limit: Optional[:class:`int`] The number of guilds to retrieve. If ``None``, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to 100. before: :class:`.abc.Snowflake` or :class:`datetime.datetime` Retrieves guilds before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time. after: :class:`.abc.Snowflake` or :class:`datetime.datetime` Retrieve guilds after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time. Raises ------ HTTPException Getting the guilds failed. Yields -------- :class:`.Guild` The guild with the guild data parsed. Examples --------- Usage :: async for guild in client.fetch_guilds(limit=150): print(guild.name) Flattening into a list :: guilds = await client.fetch_guilds(limit=150).flatten() # guilds is now a list of Guild... """ return GuildIterator(self, limit=limit, before=before, after=after)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L826-L879
[ "def", "fetch_guilds", "(", "self", ",", "*", ",", "limit", "=", "100", ",", "before", "=", "None", ",", "after", "=", "None", ")", ":", "return", "GuildIterator", "(", "self", ",", "limit", "=", "limit", ",", "before", "=", "before", ",", "after", ...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.fetch_guild
|coro| Retrieves a :class:`.Guild` from an ID. .. note:: Using this, you will not receive :attr:`.Guild.channels`, :class:`.Guild.members`, :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`. .. note:: This method is an API call. For general usage, consider :meth:`get_guild` instead. Parameters ----------- guild_id: :class:`int` The guild's ID to fetch from. Raises ------ Forbidden You do not have access to the guild. HTTPException Getting the guild failed. Returns -------- :class:`.Guild` The guild from the ID.
discord/client.py
async def fetch_guild(self, guild_id): """|coro| Retrieves a :class:`.Guild` from an ID. .. note:: Using this, you will not receive :attr:`.Guild.channels`, :class:`.Guild.members`, :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`. .. note:: This method is an API call. For general usage, consider :meth:`get_guild` instead. Parameters ----------- guild_id: :class:`int` The guild's ID to fetch from. Raises ------ Forbidden You do not have access to the guild. HTTPException Getting the guild failed. Returns -------- :class:`.Guild` The guild from the ID. """ data = await self.http.get_guild(guild_id) return Guild(data=data, state=self._connection)
async def fetch_guild(self, guild_id): """|coro| Retrieves a :class:`.Guild` from an ID. .. note:: Using this, you will not receive :attr:`.Guild.channels`, :class:`.Guild.members`, :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`. .. note:: This method is an API call. For general usage, consider :meth:`get_guild` instead. Parameters ----------- guild_id: :class:`int` The guild's ID to fetch from. Raises ------ Forbidden You do not have access to the guild. HTTPException Getting the guild failed. Returns -------- :class:`.Guild` The guild from the ID. """ data = await self.http.get_guild(guild_id) return Guild(data=data, state=self._connection)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L881-L913
[ "async", "def", "fetch_guild", "(", "self", ",", "guild_id", ")", ":", "data", "=", "await", "self", ".", "http", ".", "get_guild", "(", "guild_id", ")", "return", "Guild", "(", "data", "=", "data", ",", "state", "=", "self", ".", "_connection", ")" ]
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.create_guild
|coro| Creates a :class:`.Guild`. Bot accounts in more than 10 guilds are not allowed to create guilds. Parameters ---------- name: :class:`str` The name of the guild. region: :class:`VoiceRegion` The region for the voice communication server. Defaults to :attr:`.VoiceRegion.us_west`. icon: :class:`bytes` The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit` for more details on what is expected. Raises ------ HTTPException Guild creation failed. InvalidArgument Invalid icon image format given. Must be PNG or JPG. Returns ------- :class:`.Guild` The guild created. This is not the same guild that is added to cache.
discord/client.py
async def create_guild(self, name, region=None, icon=None): """|coro| Creates a :class:`.Guild`. Bot accounts in more than 10 guilds are not allowed to create guilds. Parameters ---------- name: :class:`str` The name of the guild. region: :class:`VoiceRegion` The region for the voice communication server. Defaults to :attr:`.VoiceRegion.us_west`. icon: :class:`bytes` The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit` for more details on what is expected. Raises ------ HTTPException Guild creation failed. InvalidArgument Invalid icon image format given. Must be PNG or JPG. Returns ------- :class:`.Guild` The guild created. This is not the same guild that is added to cache. """ if icon is not None: icon = utils._bytes_to_base64_data(icon) if region is None: region = VoiceRegion.us_west.value else: region = region.value data = await self.http.create_guild(name, region, icon) return Guild(data=data, state=self._connection)
async def create_guild(self, name, region=None, icon=None): """|coro| Creates a :class:`.Guild`. Bot accounts in more than 10 guilds are not allowed to create guilds. Parameters ---------- name: :class:`str` The name of the guild. region: :class:`VoiceRegion` The region for the voice communication server. Defaults to :attr:`.VoiceRegion.us_west`. icon: :class:`bytes` The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit` for more details on what is expected. Raises ------ HTTPException Guild creation failed. InvalidArgument Invalid icon image format given. Must be PNG or JPG. Returns ------- :class:`.Guild` The guild created. This is not the same guild that is added to cache. """ if icon is not None: icon = utils._bytes_to_base64_data(icon) if region is None: region = VoiceRegion.us_west.value else: region = region.value data = await self.http.create_guild(name, region, icon) return Guild(data=data, state=self._connection)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L915-L955
[ "async", "def", "create_guild", "(", "self", ",", "name", ",", "region", "=", "None", ",", "icon", "=", "None", ")", ":", "if", "icon", "is", "not", "None", ":", "icon", "=", "utils", ".", "_bytes_to_base64_data", "(", "icon", ")", "if", "region", "i...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
train
Client.fetch_invite
|coro| Gets an :class:`.Invite` from a discord.gg URL or ID. .. note:: If the invite is for a guild you have not joined, the guild and channel attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` and :class:`PartialInviteChannel` respectively. Parameters ----------- url: :class:`str` The discord invite ID or URL (must be a discord.gg URL). with_counts: :class:`bool` Whether to include count information in the invite. This fills the :attr:`.Invite.approximate_member_count` and :attr:`.Invite.approximate_presence_count` fields. Raises ------- NotFound The invite has expired or is invalid. HTTPException Getting the invite failed. Returns -------- :class:`.Invite` The invite from the URL/ID.
discord/client.py
async def fetch_invite(self, url, *, with_counts=True): """|coro| Gets an :class:`.Invite` from a discord.gg URL or ID. .. note:: If the invite is for a guild you have not joined, the guild and channel attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` and :class:`PartialInviteChannel` respectively. Parameters ----------- url: :class:`str` The discord invite ID or URL (must be a discord.gg URL). with_counts: :class:`bool` Whether to include count information in the invite. This fills the :attr:`.Invite.approximate_member_count` and :attr:`.Invite.approximate_presence_count` fields. Raises ------- NotFound The invite has expired or is invalid. HTTPException Getting the invite failed. Returns -------- :class:`.Invite` The invite from the URL/ID. """ invite_id = utils.resolve_invite(url) data = await self.http.get_invite(invite_id, with_counts=with_counts) return Invite.from_incomplete(state=self._connection, data=data)
async def fetch_invite(self, url, *, with_counts=True): """|coro| Gets an :class:`.Invite` from a discord.gg URL or ID. .. note:: If the invite is for a guild you have not joined, the guild and channel attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` and :class:`PartialInviteChannel` respectively. Parameters ----------- url: :class:`str` The discord invite ID or URL (must be a discord.gg URL). with_counts: :class:`bool` Whether to include count information in the invite. This fills the :attr:`.Invite.approximate_member_count` and :attr:`.Invite.approximate_presence_count` fields. Raises ------- NotFound The invite has expired or is invalid. HTTPException Getting the invite failed. Returns -------- :class:`.Invite` The invite from the URL/ID. """ invite_id = utils.resolve_invite(url) data = await self.http.get_invite(invite_id, with_counts=with_counts) return Invite.from_incomplete(state=self._connection, data=data)
[ "|coro|" ]
Rapptz/discord.py
python
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L959-L994
[ "async", "def", "fetch_invite", "(", "self", ",", "url", ",", "*", ",", "with_counts", "=", "True", ")", ":", "invite_id", "=", "utils", ".", "resolve_invite", "(", "url", ")", "data", "=", "await", "self", ".", "http", ".", "get_invite", "(", "invite_...
05d4f7f9620ef33635d6ac965b26528e09cdaf5b