repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
DefaultHelpCommand.send_pages
|
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)
|
python
|
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",
")",
":",
"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.
|
[
"A",
"helper",
"utility",
"to",
"send",
"the",
"page",
"output",
"from",
":",
"attr",
":",
"paginator",
"to",
"the",
"destination",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L913-L917
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
MinimalHelpCommand.add_bot_commands_formatting
|
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)
|
python
|
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",
")",
":",
"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.
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.
|
[
"Adds",
"the",
"minified",
"bot",
"heading",
"with",
"commands",
"to",
"the",
"output",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L1092-L1111
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
MinimalHelpCommand.add_subcommand_formatting
|
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))
|
python
|
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",
")",
":",
"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.
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.
|
[
"Adds",
"formatting",
"information",
"on",
"a",
"subcommand",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L1113-L1127
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
MinimalHelpCommand.add_aliases_formatting
|
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)
|
python
|
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",
")",
":",
"self",
".",
"paginator",
".",
"add_line",
"(",
"'**%s** %s'",
"%",
"(",
"self",
".",
"aliases_heading",
",",
"', '",
".",
"join",
"(",
"aliases",
")",
")",
",",
"empty",
"=",
"True",
")"
] |
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.
|
[
"Adds",
"the",
"formatting",
"information",
"on",
"a",
"command",
"s",
"aliases",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L1129-L1144
|
train
|
Rapptz/discord.py
|
discord/ext/commands/help.py
|
MinimalHelpCommand.add_command_formatting
|
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()
|
python
|
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",
")",
":",
"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.
Parameters
------------
command: :class:`Command`
The command to format.
|
[
"A",
"utility",
"function",
"to",
"format",
"commands",
"and",
"groups",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L1146-L1171
|
train
|
Rapptz/discord.py
|
discord/voice_client.py
|
VoiceClient.disconnect
|
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()
|
python
|
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",
")",
":",
"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|
Disconnects this voice client from voice.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/voice_client.py#L269-L287
|
train
|
Rapptz/discord.py
|
discord/voice_client.py
|
VoiceClient.move_to
|
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)
|
python
|
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",
")",
":",
"guild_id",
",",
"_",
"=",
"self",
".",
"channel",
".",
"_get_voice_state_pair",
"(",
")",
"await",
"self",
".",
"main_ws",
".",
"voice_state",
"(",
"guild_id",
",",
"channel",
".",
"id",
")"
] |
|coro|
Moves you to a different voice channel.
Parameters
-----------
channel: :class:`abc.Snowflake`
The channel to move to. Must be a voice channel.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/voice_client.py#L289-L300
|
train
|
Rapptz/discord.py
|
discord/voice_client.py
|
VoiceClient.play
|
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()
|
python
|
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",
")",
":",
"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`.
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.
|
[
"Plays",
"an",
":",
"class",
":",
"AudioSource",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/voice_client.py#L334-L371
|
train
|
Rapptz/discord.py
|
discord/voice_client.py
|
VoiceClient.send_audio_packet
|
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)
|
python
|
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",
")",
":",
"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.
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.
|
[
"Sends",
"an",
"audio",
"packet",
"composed",
"of",
"the",
"data",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/voice_client.py#L415-L446
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.on_error
|
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()
|
python
|
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",
")",
":",
"print",
"(",
"'Ignoring exception in {}'",
".",
"format",
"(",
"event_method",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"traceback",
".",
"print_exc",
"(",
")"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L300-L310
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.request_offline_members
|
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)
|
python
|
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",
")",
":",
"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|
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.
|
[
"r",
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L312-L338
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.login
|
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
|
python
|
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",
")",
":",
"log",
".",
"info",
"(",
"'logging in using static token'",
")",
"await",
"self",
".",
"http",
".",
"static_login",
"(",
"token",
",",
"bot",
"=",
"bot",
")",
"self",
".",
"_connection",
".",
"is_bot",
"=",
"bot"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L342-L377
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.connect
|
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)
|
python
|
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",
")",
":",
"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|
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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L405-L465
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.close
|
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()
|
python
|
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",
")",
":",
"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|
Closes the connection to discord.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L467-L488
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.clear
|
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()
|
python
|
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",
")",
":",
"self",
".",
"_closed",
"=",
"False",
"self",
".",
"_ready",
".",
"clear",
"(",
")",
"self",
".",
"_connection",
".",
"clear",
"(",
")",
"self",
".",
"http",
".",
"recreate",
"(",
")"
] |
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.
|
[
"Clears",
"the",
"internal",
"state",
"of",
"the",
"bot",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L490-L500
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.start
|
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)
|
python
|
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",
")",
":",
"bot",
"=",
"kwargs",
".",
"pop",
"(",
"'bot'",
",",
"True",
")",
"reconnect",
"=",
"kwargs",
".",
"pop",
"(",
"'reconnect'",
",",
"True",
")",
"await",
"self",
".",
"login",
"(",
"*",
"args",
",",
"bot",
"=",
"bot",
")",
"await",
"self",
".",
"connect",
"(",
"reconnect",
"=",
"reconnect",
")"
] |
|coro|
A shorthand coroutine for :meth:`login` + :meth:`connect`.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L502-L511
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.run
|
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)
|
python
|
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",
")",
":",
"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.
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.
|
[
"A",
"blocking",
"call",
"that",
"abstracts",
"away",
"the",
"event",
"loop",
"initialisation",
"from",
"you",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L513-L549
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.wait_for
|
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)
|
python
|
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",
")",
":",
"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|
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>`.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L640-L736
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.event
|
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
|
python
|
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",
")",
":",
"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.
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.
|
[
"A",
"decorator",
"that",
"registers",
"an",
"event",
"to",
"listen",
"to",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L740-L767
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.change_presence
|
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
|
python
|
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",
")",
":",
"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|
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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L769-L822
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.fetch_guilds
|
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)
|
python
|
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",
")",
":",
"return",
"GuildIterator",
"(",
"self",
",",
"limit",
"=",
"limit",
",",
"before",
"=",
"before",
",",
"after",
"=",
"after",
")"
] |
|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...
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L826-L879
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.fetch_guild
|
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)
|
python
|
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",
")",
":",
"data",
"=",
"await",
"self",
".",
"http",
".",
"get_guild",
"(",
"guild_id",
")",
"return",
"Guild",
"(",
"data",
"=",
"data",
",",
"state",
"=",
"self",
".",
"_connection",
")"
] |
|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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L881-L913
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.create_guild
|
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)
|
python
|
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",
")",
":",
"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|
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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L915-L955
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.fetch_invite
|
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)
|
python
|
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",
")",
":",
"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|
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.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L959-L994
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.delete_invite
|
async def delete_invite(self, invite):
"""|coro|
Revokes an :class:`.Invite`, URL, or ID to an invite.
You must have the :attr:`~.Permissions.manage_channels` permission in
the associated guild to do this.
Parameters
----------
invite: Union[:class:`.Invite`, :class:`str`]
The invite to revoke.
Raises
-------
Forbidden
You do not have permissions to revoke invites.
NotFound
The invite is invalid or expired.
HTTPException
Revoking the invite failed.
"""
invite_id = utils.resolve_invite(invite)
await self.http.delete_invite(invite_id)
|
python
|
async def delete_invite(self, invite):
"""|coro|
Revokes an :class:`.Invite`, URL, or ID to an invite.
You must have the :attr:`~.Permissions.manage_channels` permission in
the associated guild to do this.
Parameters
----------
invite: Union[:class:`.Invite`, :class:`str`]
The invite to revoke.
Raises
-------
Forbidden
You do not have permissions to revoke invites.
NotFound
The invite is invalid or expired.
HTTPException
Revoking the invite failed.
"""
invite_id = utils.resolve_invite(invite)
await self.http.delete_invite(invite_id)
|
[
"async",
"def",
"delete_invite",
"(",
"self",
",",
"invite",
")",
":",
"invite_id",
"=",
"utils",
".",
"resolve_invite",
"(",
"invite",
")",
"await",
"self",
".",
"http",
".",
"delete_invite",
"(",
"invite_id",
")"
] |
|coro|
Revokes an :class:`.Invite`, URL, or ID to an invite.
You must have the :attr:`~.Permissions.manage_channels` permission in
the associated guild to do this.
Parameters
----------
invite: Union[:class:`.Invite`, :class:`str`]
The invite to revoke.
Raises
-------
Forbidden
You do not have permissions to revoke invites.
NotFound
The invite is invalid or expired.
HTTPException
Revoking the invite failed.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L996-L1020
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.fetch_widget
|
async def fetch_widget(self, guild_id):
"""|coro|
Gets a :class:`.Widget` from a guild ID.
.. note::
The guild must have the widget enabled to get this information.
Parameters
-----------
guild_id: :class:`int`
The ID of the guild.
Raises
-------
Forbidden
The widget for this guild is disabled.
HTTPException
Retrieving the widget failed.
Returns
--------
:class:`.Widget`
The guild's widget.
"""
data = await self.http.get_widget(guild_id)
return Widget(state=self._connection, data=data)
|
python
|
async def fetch_widget(self, guild_id):
"""|coro|
Gets a :class:`.Widget` from a guild ID.
.. note::
The guild must have the widget enabled to get this information.
Parameters
-----------
guild_id: :class:`int`
The ID of the guild.
Raises
-------
Forbidden
The widget for this guild is disabled.
HTTPException
Retrieving the widget failed.
Returns
--------
:class:`.Widget`
The guild's widget.
"""
data = await self.http.get_widget(guild_id)
return Widget(state=self._connection, data=data)
|
[
"async",
"def",
"fetch_widget",
"(",
"self",
",",
"guild_id",
")",
":",
"data",
"=",
"await",
"self",
".",
"http",
".",
"get_widget",
"(",
"guild_id",
")",
"return",
"Widget",
"(",
"state",
"=",
"self",
".",
"_connection",
",",
"data",
"=",
"data",
")"
] |
|coro|
Gets a :class:`.Widget` from a guild ID.
.. note::
The guild must have the widget enabled to get this information.
Parameters
-----------
guild_id: :class:`int`
The ID of the guild.
Raises
-------
Forbidden
The widget for this guild is disabled.
HTTPException
Retrieving the widget failed.
Returns
--------
:class:`.Widget`
The guild's widget.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L1024-L1052
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.application_info
|
async def application_info(self):
"""|coro|
Retrieve's the bot's application information.
Raises
-------
HTTPException
Retrieving the information failed somehow.
Returns
--------
:class:`.AppInfo`
A namedtuple representing the application info.
"""
data = await self.http.application_info()
if 'rpc_origins' not in data:
data['rpc_origins'] = None
return AppInfo(self._connection, data)
|
python
|
async def application_info(self):
"""|coro|
Retrieve's the bot's application information.
Raises
-------
HTTPException
Retrieving the information failed somehow.
Returns
--------
:class:`.AppInfo`
A namedtuple representing the application info.
"""
data = await self.http.application_info()
if 'rpc_origins' not in data:
data['rpc_origins'] = None
return AppInfo(self._connection, data)
|
[
"async",
"def",
"application_info",
"(",
"self",
")",
":",
"data",
"=",
"await",
"self",
".",
"http",
".",
"application_info",
"(",
")",
"if",
"'rpc_origins'",
"not",
"in",
"data",
":",
"data",
"[",
"'rpc_origins'",
"]",
"=",
"None",
"return",
"AppInfo",
"(",
"self",
".",
"_connection",
",",
"data",
")"
] |
|coro|
Retrieve's the bot's application information.
Raises
-------
HTTPException
Retrieving the information failed somehow.
Returns
--------
:class:`.AppInfo`
A namedtuple representing the application info.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L1054-L1072
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.fetch_user
|
async def fetch_user(self, user_id):
"""|coro|
Retrieves a :class:`~discord.User` based on their ID. This can only
be used by bot accounts. You do not have to share any guilds
with the user to get this information, however many operations
do require that you do.
.. note::
This method is an API call. For general usage, consider :meth:`get_user` instead.
Parameters
-----------
user_id: :class:`int`
The user's ID to fetch from.
Raises
-------
NotFound
A user with this ID does not exist.
HTTPException
Fetching the user failed.
Returns
--------
:class:`~discord.User`
The user you requested.
"""
data = await self.http.get_user(user_id)
return User(state=self._connection, data=data)
|
python
|
async def fetch_user(self, user_id):
"""|coro|
Retrieves a :class:`~discord.User` based on their ID. This can only
be used by bot accounts. You do not have to share any guilds
with the user to get this information, however many operations
do require that you do.
.. note::
This method is an API call. For general usage, consider :meth:`get_user` instead.
Parameters
-----------
user_id: :class:`int`
The user's ID to fetch from.
Raises
-------
NotFound
A user with this ID does not exist.
HTTPException
Fetching the user failed.
Returns
--------
:class:`~discord.User`
The user you requested.
"""
data = await self.http.get_user(user_id)
return User(state=self._connection, data=data)
|
[
"async",
"def",
"fetch_user",
"(",
"self",
",",
"user_id",
")",
":",
"data",
"=",
"await",
"self",
".",
"http",
".",
"get_user",
"(",
"user_id",
")",
"return",
"User",
"(",
"state",
"=",
"self",
".",
"_connection",
",",
"data",
"=",
"data",
")"
] |
|coro|
Retrieves a :class:`~discord.User` based on their ID. This can only
be used by bot accounts. You do not have to share any guilds
with the user to get this information, however many operations
do require that you do.
.. note::
This method is an API call. For general usage, consider :meth:`get_user` instead.
Parameters
-----------
user_id: :class:`int`
The user's ID to fetch from.
Raises
-------
NotFound
A user with this ID does not exist.
HTTPException
Fetching the user failed.
Returns
--------
:class:`~discord.User`
The user you requested.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L1074-L1104
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.fetch_user_profile
|
async def fetch_user_profile(self, user_id):
"""|coro|
Gets an arbitrary user's profile. This can only be used by non-bot accounts.
Parameters
------------
user_id: :class:`int`
The ID of the user to fetch their profile for.
Raises
-------
Forbidden
Not allowed to fetch profiles.
HTTPException
Fetching the profile failed.
Returns
--------
:class:`.Profile`
The profile of the user.
"""
state = self._connection
data = await self.http.get_user_profile(user_id)
def transform(d):
return state._get_guild(int(d['id']))
since = data.get('premium_since')
mutual_guilds = list(filter(None, map(transform, data.get('mutual_guilds', []))))
user = data['user']
return Profile(flags=user.get('flags', 0),
premium_since=utils.parse_time(since),
mutual_guilds=mutual_guilds,
user=User(data=user, state=state),
connected_accounts=data['connected_accounts'])
|
python
|
async def fetch_user_profile(self, user_id):
"""|coro|
Gets an arbitrary user's profile. This can only be used by non-bot accounts.
Parameters
------------
user_id: :class:`int`
The ID of the user to fetch their profile for.
Raises
-------
Forbidden
Not allowed to fetch profiles.
HTTPException
Fetching the profile failed.
Returns
--------
:class:`.Profile`
The profile of the user.
"""
state = self._connection
data = await self.http.get_user_profile(user_id)
def transform(d):
return state._get_guild(int(d['id']))
since = data.get('premium_since')
mutual_guilds = list(filter(None, map(transform, data.get('mutual_guilds', []))))
user = data['user']
return Profile(flags=user.get('flags', 0),
premium_since=utils.parse_time(since),
mutual_guilds=mutual_guilds,
user=User(data=user, state=state),
connected_accounts=data['connected_accounts'])
|
[
"async",
"def",
"fetch_user_profile",
"(",
"self",
",",
"user_id",
")",
":",
"state",
"=",
"self",
".",
"_connection",
"data",
"=",
"await",
"self",
".",
"http",
".",
"get_user_profile",
"(",
"user_id",
")",
"def",
"transform",
"(",
"d",
")",
":",
"return",
"state",
".",
"_get_guild",
"(",
"int",
"(",
"d",
"[",
"'id'",
"]",
")",
")",
"since",
"=",
"data",
".",
"get",
"(",
"'premium_since'",
")",
"mutual_guilds",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"map",
"(",
"transform",
",",
"data",
".",
"get",
"(",
"'mutual_guilds'",
",",
"[",
"]",
")",
")",
")",
")",
"user",
"=",
"data",
"[",
"'user'",
"]",
"return",
"Profile",
"(",
"flags",
"=",
"user",
".",
"get",
"(",
"'flags'",
",",
"0",
")",
",",
"premium_since",
"=",
"utils",
".",
"parse_time",
"(",
"since",
")",
",",
"mutual_guilds",
"=",
"mutual_guilds",
",",
"user",
"=",
"User",
"(",
"data",
"=",
"user",
",",
"state",
"=",
"state",
")",
",",
"connected_accounts",
"=",
"data",
"[",
"'connected_accounts'",
"]",
")"
] |
|coro|
Gets an arbitrary user's profile. This can only be used by non-bot accounts.
Parameters
------------
user_id: :class:`int`
The ID of the user to fetch their profile for.
Raises
-------
Forbidden
Not allowed to fetch profiles.
HTTPException
Fetching the profile failed.
Returns
--------
:class:`.Profile`
The profile of the user.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L1106-L1142
|
train
|
Rapptz/discord.py
|
discord/client.py
|
Client.fetch_webhook
|
async def fetch_webhook(self, webhook_id):
"""|coro|
Retrieves a :class:`.Webhook` with the specified ID.
Raises
--------
HTTPException
Retrieving the webhook failed.
NotFound
Invalid webhook ID.
Forbidden
You do not have permission to fetch this webhook.
Returns
---------
:class:`.Webhook`
The webhook you requested.
"""
data = await self.http.get_webhook(webhook_id)
return Webhook.from_state(data, state=self._connection)
|
python
|
async def fetch_webhook(self, webhook_id):
"""|coro|
Retrieves a :class:`.Webhook` with the specified ID.
Raises
--------
HTTPException
Retrieving the webhook failed.
NotFound
Invalid webhook ID.
Forbidden
You do not have permission to fetch this webhook.
Returns
---------
:class:`.Webhook`
The webhook you requested.
"""
data = await self.http.get_webhook(webhook_id)
return Webhook.from_state(data, state=self._connection)
|
[
"async",
"def",
"fetch_webhook",
"(",
"self",
",",
"webhook_id",
")",
":",
"data",
"=",
"await",
"self",
".",
"http",
".",
"get_webhook",
"(",
"webhook_id",
")",
"return",
"Webhook",
".",
"from_state",
"(",
"data",
",",
"state",
"=",
"self",
".",
"_connection",
")"
] |
|coro|
Retrieves a :class:`.Webhook` with the specified ID.
Raises
--------
HTTPException
Retrieving the webhook failed.
NotFound
Invalid webhook ID.
Forbidden
You do not have permission to fetch this webhook.
Returns
---------
:class:`.Webhook`
The webhook you requested.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L1144-L1164
|
train
|
Rapptz/discord.py
|
discord/invite.py
|
PartialInviteGuild.icon_url_as
|
def icon_url_as(self, *, format='webp', size=1024):
""":class:`Asset`: The same operation as :meth:`Guild.icon_url_as`."""
return Asset._from_guild_image(self._state, self.id, self.icon, 'icons', format=format, size=size)
|
python
|
def icon_url_as(self, *, format='webp', size=1024):
""":class:`Asset`: The same operation as :meth:`Guild.icon_url_as`."""
return Asset._from_guild_image(self._state, self.id, self.icon, 'icons', format=format, size=size)
|
[
"def",
"icon_url_as",
"(",
"self",
",",
"*",
",",
"format",
"=",
"'webp'",
",",
"size",
"=",
"1024",
")",
":",
"return",
"Asset",
".",
"_from_guild_image",
"(",
"self",
".",
"_state",
",",
"self",
".",
"id",
",",
"self",
".",
"icon",
",",
"'icons'",
",",
"format",
"=",
"format",
",",
"size",
"=",
"size",
")"
] |
:class:`Asset`: The same operation as :meth:`Guild.icon_url_as`.
|
[
":",
"class",
":",
"Asset",
":",
"The",
"same",
"operation",
"as",
":",
"meth",
":",
"Guild",
".",
"icon_url_as",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/invite.py#L153-L155
|
train
|
Rapptz/discord.py
|
discord/invite.py
|
PartialInviteGuild.banner_url_as
|
def banner_url_as(self, *, format='webp', size=2048):
""":class:`Asset`: The same operation as :meth:`Guild.banner_url_as`."""
return Asset._from_guild_image(self._state, self.id, self.banner, 'banners', format=format, size=size)
|
python
|
def banner_url_as(self, *, format='webp', size=2048):
""":class:`Asset`: The same operation as :meth:`Guild.banner_url_as`."""
return Asset._from_guild_image(self._state, self.id, self.banner, 'banners', format=format, size=size)
|
[
"def",
"banner_url_as",
"(",
"self",
",",
"*",
",",
"format",
"=",
"'webp'",
",",
"size",
"=",
"2048",
")",
":",
"return",
"Asset",
".",
"_from_guild_image",
"(",
"self",
".",
"_state",
",",
"self",
".",
"id",
",",
"self",
".",
"banner",
",",
"'banners'",
",",
"format",
"=",
"format",
",",
"size",
"=",
"size",
")"
] |
:class:`Asset`: The same operation as :meth:`Guild.banner_url_as`.
|
[
":",
"class",
":",
"Asset",
":",
"The",
"same",
"operation",
"as",
":",
"meth",
":",
"Guild",
".",
"banner_url_as",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/invite.py#L162-L164
|
train
|
Rapptz/discord.py
|
discord/invite.py
|
PartialInviteGuild.splash_url_as
|
def splash_url_as(self, *, format='webp', size=2048):
""":class:`Asset`: The same operation as :meth:`Guild.splash_url_as`."""
return Asset._from_guild_image(self._state, self.id, self.splash, 'splashes', format=format, size=size)
|
python
|
def splash_url_as(self, *, format='webp', size=2048):
""":class:`Asset`: The same operation as :meth:`Guild.splash_url_as`."""
return Asset._from_guild_image(self._state, self.id, self.splash, 'splashes', format=format, size=size)
|
[
"def",
"splash_url_as",
"(",
"self",
",",
"*",
",",
"format",
"=",
"'webp'",
",",
"size",
"=",
"2048",
")",
":",
"return",
"Asset",
".",
"_from_guild_image",
"(",
"self",
".",
"_state",
",",
"self",
".",
"id",
",",
"self",
".",
"splash",
",",
"'splashes'",
",",
"format",
"=",
"format",
",",
"size",
"=",
"size",
")"
] |
:class:`Asset`: The same operation as :meth:`Guild.splash_url_as`.
|
[
":",
"class",
":",
"Asset",
":",
"The",
"same",
"operation",
"as",
":",
"meth",
":",
"Guild",
".",
"splash_url_as",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/invite.py#L171-L173
|
train
|
Rapptz/discord.py
|
discord/invite.py
|
Invite.delete
|
async def delete(self, *, reason=None):
"""|coro|
Revokes the instant invite.
You must have the :attr:`~Permissions.manage_channels` permission to do this.
Parameters
-----------
reason: Optional[:class:`str`]
The reason for deleting this invite. Shows up on the audit log.
Raises
-------
Forbidden
You do not have permissions to revoke invites.
NotFound
The invite is invalid or expired.
HTTPException
Revoking the invite failed.
"""
await self._state.http.delete_invite(self.code, reason=reason)
|
python
|
async def delete(self, *, reason=None):
"""|coro|
Revokes the instant invite.
You must have the :attr:`~Permissions.manage_channels` permission to do this.
Parameters
-----------
reason: Optional[:class:`str`]
The reason for deleting this invite. Shows up on the audit log.
Raises
-------
Forbidden
You do not have permissions to revoke invites.
NotFound
The invite is invalid or expired.
HTTPException
Revoking the invite failed.
"""
await self._state.http.delete_invite(self.code, reason=reason)
|
[
"async",
"def",
"delete",
"(",
"self",
",",
"*",
",",
"reason",
"=",
"None",
")",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"delete_invite",
"(",
"self",
".",
"code",
",",
"reason",
"=",
"reason",
")"
] |
|coro|
Revokes the instant invite.
You must have the :attr:`~Permissions.manage_channels` permission to do this.
Parameters
-----------
reason: Optional[:class:`str`]
The reason for deleting this invite. Shows up on the audit log.
Raises
-------
Forbidden
You do not have permissions to revoke invites.
NotFound
The invite is invalid or expired.
HTTPException
Revoking the invite failed.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/invite.py#L286-L308
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Attachment.save
|
async def save(self, fp, *, seek_begin=True, use_cached=False):
"""|coro|
Saves this attachment into a file-like object.
Parameters
-----------
fp: Union[BinaryIO, :class:`os.PathLike`]
The file-like object to save this attachment to or the filename
to use. If a filename is passed then a file is created with that
filename and used instead.
seek_begin: :class:`bool`
Whether to seek to the beginning of the file after saving is
successfully done.
use_cached: :class:`bool`
Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading
the attachment. This will allow attachments to be saved after deletion
more often, compared to the regular URL which is generally deleted right
after the message is deleted. Note that this can still fail to download
deleted attachments if too much time has passed and it does not work
on some type of attachments.
Raises
--------
HTTPException
Saving the attachment failed.
NotFound
The attachment was deleted.
Returns
--------
:class:`int`
The number of bytes written.
"""
url = self.proxy_url if use_cached else self.url
data = await self._http.get_from_cdn(url)
if isinstance(fp, io.IOBase) and fp.writable():
written = fp.write(data)
if seek_begin:
fp.seek(0)
return written
else:
with open(fp, 'wb') as f:
return f.write(data)
|
python
|
async def save(self, fp, *, seek_begin=True, use_cached=False):
"""|coro|
Saves this attachment into a file-like object.
Parameters
-----------
fp: Union[BinaryIO, :class:`os.PathLike`]
The file-like object to save this attachment to or the filename
to use. If a filename is passed then a file is created with that
filename and used instead.
seek_begin: :class:`bool`
Whether to seek to the beginning of the file after saving is
successfully done.
use_cached: :class:`bool`
Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading
the attachment. This will allow attachments to be saved after deletion
more often, compared to the regular URL which is generally deleted right
after the message is deleted. Note that this can still fail to download
deleted attachments if too much time has passed and it does not work
on some type of attachments.
Raises
--------
HTTPException
Saving the attachment failed.
NotFound
The attachment was deleted.
Returns
--------
:class:`int`
The number of bytes written.
"""
url = self.proxy_url if use_cached else self.url
data = await self._http.get_from_cdn(url)
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",
",",
"use_cached",
"=",
"False",
")",
":",
"url",
"=",
"self",
".",
"proxy_url",
"if",
"use_cached",
"else",
"self",
".",
"url",
"data",
"=",
"await",
"self",
".",
"_http",
".",
"get_from_cdn",
"(",
"url",
")",
"if",
"isinstance",
"(",
"fp",
",",
"io",
".",
"IOBase",
")",
"and",
"fp",
".",
"writable",
"(",
")",
":",
"written",
"=",
"fp",
".",
"write",
"(",
"data",
")",
"if",
"seek_begin",
":",
"fp",
".",
"seek",
"(",
"0",
")",
"return",
"written",
"else",
":",
"with",
"open",
"(",
"fp",
",",
"'wb'",
")",
"as",
"f",
":",
"return",
"f",
".",
"write",
"(",
"data",
")"
] |
|coro|
Saves this attachment into a file-like object.
Parameters
-----------
fp: Union[BinaryIO, :class:`os.PathLike`]
The file-like object to save this attachment to or the filename
to use. If a filename is passed then a file is created with that
filename and used instead.
seek_begin: :class:`bool`
Whether to seek to the beginning of the file after saving is
successfully done.
use_cached: :class:`bool`
Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading
the attachment. This will allow attachments to be saved after deletion
more often, compared to the regular URL which is generally deleted right
after the message is deleted. Note that this can still fail to download
deleted attachments if too much time has passed and it does not work
on some type of attachments.
Raises
--------
HTTPException
Saving the attachment failed.
NotFound
The attachment was deleted.
Returns
--------
:class:`int`
The number of bytes written.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L81-L124
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Message.raw_mentions
|
def raw_mentions(self):
"""A property that returns an array of user IDs matched with
the syntax of <@user_id> in the message content.
This allows you to receive the user IDs of mentioned users
even in a private message context.
"""
return [int(x) for x in re.findall(r'<@!?([0-9]+)>', self.content)]
|
python
|
def raw_mentions(self):
"""A property that returns an array of user IDs matched with
the syntax of <@user_id> in the message content.
This allows you to receive the user IDs of mentioned users
even in a private message context.
"""
return [int(x) for x in re.findall(r'<@!?([0-9]+)>', self.content)]
|
[
"def",
"raw_mentions",
"(",
"self",
")",
":",
"return",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"re",
".",
"findall",
"(",
"r'<@!?([0-9]+)>'",
",",
"self",
".",
"content",
")",
"]"
] |
A property that returns an array of user IDs matched with
the syntax of <@user_id> in the message content.
This allows you to receive the user IDs of mentioned users
even in a private message context.
|
[
"A",
"property",
"that",
"returns",
"an",
"array",
"of",
"user",
"IDs",
"matched",
"with",
"the",
"syntax",
"of",
"<@user_id",
">",
"in",
"the",
"message",
"content",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L370-L377
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Message.raw_channel_mentions
|
def raw_channel_mentions(self):
"""A property that returns an array of channel IDs matched with
the syntax of <#channel_id> in the message content.
"""
return [int(x) for x in re.findall(r'<#([0-9]+)>', self.content)]
|
python
|
def raw_channel_mentions(self):
"""A property that returns an array of channel IDs matched with
the syntax of <#channel_id> in the message content.
"""
return [int(x) for x in re.findall(r'<#([0-9]+)>', self.content)]
|
[
"def",
"raw_channel_mentions",
"(",
"self",
")",
":",
"return",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"re",
".",
"findall",
"(",
"r'<#([0-9]+)>'",
",",
"self",
".",
"content",
")",
"]"
] |
A property that returns an array of channel IDs matched with
the syntax of <#channel_id> in the message content.
|
[
"A",
"property",
"that",
"returns",
"an",
"array",
"of",
"channel",
"IDs",
"matched",
"with",
"the",
"syntax",
"of",
"<#channel_id",
">",
"in",
"the",
"message",
"content",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L380-L384
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Message.raw_role_mentions
|
def raw_role_mentions(self):
"""A property that returns an array of role IDs matched with
the syntax of <@&role_id> in the message content.
"""
return [int(x) for x in re.findall(r'<@&([0-9]+)>', self.content)]
|
python
|
def raw_role_mentions(self):
"""A property that returns an array of role IDs matched with
the syntax of <@&role_id> in the message content.
"""
return [int(x) for x in re.findall(r'<@&([0-9]+)>', self.content)]
|
[
"def",
"raw_role_mentions",
"(",
"self",
")",
":",
"return",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"re",
".",
"findall",
"(",
"r'<@&([0-9]+)>'",
",",
"self",
".",
"content",
")",
"]"
] |
A property that returns an array of role IDs matched with
the syntax of <@&role_id> in the message content.
|
[
"A",
"property",
"that",
"returns",
"an",
"array",
"of",
"role",
"IDs",
"matched",
"with",
"the",
"syntax",
"of",
"<"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L387-L391
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Message.clean_content
|
def clean_content(self):
"""A property that returns the content in a "cleaned up"
manner. This basically means that mentions are transformed
into the way the client shows it. e.g. ``<#id>`` will transform
into ``#name``.
This will also transform @everyone and @here mentions into
non-mentions.
.. note::
This *does not* escape markdown. If you want to escape
markdown then use :func:`utils.escape_markdown` along
with this function.
"""
transformations = {
re.escape('<#%s>' % channel.id): '#' + channel.name
for channel in self.channel_mentions
}
mention_transforms = {
re.escape('<@%s>' % member.id): '@' + member.display_name
for member in self.mentions
}
# add the <@!user_id> cases as well..
second_mention_transforms = {
re.escape('<@!%s>' % member.id): '@' + member.display_name
for member in self.mentions
}
transformations.update(mention_transforms)
transformations.update(second_mention_transforms)
if self.guild is not None:
role_transforms = {
re.escape('<@&%s>' % role.id): '@' + role.name
for role in self.role_mentions
}
transformations.update(role_transforms)
def repl(obj):
return transformations.get(re.escape(obj.group(0)), '')
pattern = re.compile('|'.join(transformations.keys()))
result = pattern.sub(repl, self.content)
transformations = {
'@everyone': '@\u200beveryone',
'@here': '@\u200bhere'
}
def repl2(obj):
return transformations.get(obj.group(0), '')
pattern = re.compile('|'.join(transformations.keys()))
return pattern.sub(repl2, result)
|
python
|
def clean_content(self):
"""A property that returns the content in a "cleaned up"
manner. This basically means that mentions are transformed
into the way the client shows it. e.g. ``<#id>`` will transform
into ``#name``.
This will also transform @everyone and @here mentions into
non-mentions.
.. note::
This *does not* escape markdown. If you want to escape
markdown then use :func:`utils.escape_markdown` along
with this function.
"""
transformations = {
re.escape('<#%s>' % channel.id): '#' + channel.name
for channel in self.channel_mentions
}
mention_transforms = {
re.escape('<@%s>' % member.id): '@' + member.display_name
for member in self.mentions
}
# add the <@!user_id> cases as well..
second_mention_transforms = {
re.escape('<@!%s>' % member.id): '@' + member.display_name
for member in self.mentions
}
transformations.update(mention_transforms)
transformations.update(second_mention_transforms)
if self.guild is not None:
role_transforms = {
re.escape('<@&%s>' % role.id): '@' + role.name
for role in self.role_mentions
}
transformations.update(role_transforms)
def repl(obj):
return transformations.get(re.escape(obj.group(0)), '')
pattern = re.compile('|'.join(transformations.keys()))
result = pattern.sub(repl, self.content)
transformations = {
'@everyone': '@\u200beveryone',
'@here': '@\u200bhere'
}
def repl2(obj):
return transformations.get(obj.group(0), '')
pattern = re.compile('|'.join(transformations.keys()))
return pattern.sub(repl2, result)
|
[
"def",
"clean_content",
"(",
"self",
")",
":",
"transformations",
"=",
"{",
"re",
".",
"escape",
"(",
"'<#%s>'",
"%",
"channel",
".",
"id",
")",
":",
"'#'",
"+",
"channel",
".",
"name",
"for",
"channel",
"in",
"self",
".",
"channel_mentions",
"}",
"mention_transforms",
"=",
"{",
"re",
".",
"escape",
"(",
"'<@%s>'",
"%",
"member",
".",
"id",
")",
":",
"'@'",
"+",
"member",
".",
"display_name",
"for",
"member",
"in",
"self",
".",
"mentions",
"}",
"# add the <@!user_id> cases as well..",
"second_mention_transforms",
"=",
"{",
"re",
".",
"escape",
"(",
"'<@!%s>'",
"%",
"member",
".",
"id",
")",
":",
"'@'",
"+",
"member",
".",
"display_name",
"for",
"member",
"in",
"self",
".",
"mentions",
"}",
"transformations",
".",
"update",
"(",
"mention_transforms",
")",
"transformations",
".",
"update",
"(",
"second_mention_transforms",
")",
"if",
"self",
".",
"guild",
"is",
"not",
"None",
":",
"role_transforms",
"=",
"{",
"re",
".",
"escape",
"(",
"'<@&%s>'",
"%",
"role",
".",
"id",
")",
":",
"'@'",
"+",
"role",
".",
"name",
"for",
"role",
"in",
"self",
".",
"role_mentions",
"}",
"transformations",
".",
"update",
"(",
"role_transforms",
")",
"def",
"repl",
"(",
"obj",
")",
":",
"return",
"transformations",
".",
"get",
"(",
"re",
".",
"escape",
"(",
"obj",
".",
"group",
"(",
"0",
")",
")",
",",
"''",
")",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'|'",
".",
"join",
"(",
"transformations",
".",
"keys",
"(",
")",
")",
")",
"result",
"=",
"pattern",
".",
"sub",
"(",
"repl",
",",
"self",
".",
"content",
")",
"transformations",
"=",
"{",
"'@everyone'",
":",
"'@\\u200beveryone'",
",",
"'@here'",
":",
"'@\\u200bhere'",
"}",
"def",
"repl2",
"(",
"obj",
")",
":",
"return",
"transformations",
".",
"get",
"(",
"obj",
".",
"group",
"(",
"0",
")",
",",
"''",
")",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'|'",
".",
"join",
"(",
"transformations",
".",
"keys",
"(",
")",
")",
")",
"return",
"pattern",
".",
"sub",
"(",
"repl2",
",",
"result",
")"
] |
A property that returns the content in a "cleaned up"
manner. This basically means that mentions are transformed
into the way the client shows it. e.g. ``<#id>`` will transform
into ``#name``.
This will also transform @everyone and @here mentions into
non-mentions.
.. note::
This *does not* escape markdown. If you want to escape
markdown then use :func:`utils.escape_markdown` along
with this function.
|
[
"A",
"property",
"that",
"returns",
"the",
"content",
"in",
"a",
"cleaned",
"up",
"manner",
".",
"This",
"basically",
"means",
"that",
"mentions",
"are",
"transformed",
"into",
"the",
"way",
"the",
"client",
"shows",
"it",
".",
"e",
".",
"g",
".",
"<#id",
">",
"will",
"transform",
"into",
"#name",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L401-L458
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Message.system_content
|
def system_content(self):
r"""A property that returns the content that is rendered
regardless of the :attr:`Message.type`.
In the case of :attr:`MessageType.default`\, this just returns the
regular :attr:`Message.content`. Otherwise this returns an English
message denoting the contents of the system message.
"""
if self.type is MessageType.default:
return self.content
if self.type is MessageType.pins_add:
return '{0.name} pinned a message to this channel.'.format(self.author)
if self.type is MessageType.recipient_add:
return '{0.name} added {1.name} to the group.'.format(self.author, self.mentions[0])
if self.type is MessageType.recipient_remove:
return '{0.name} removed {1.name} from the group.'.format(self.author, self.mentions[0])
if self.type is MessageType.channel_name_change:
return '{0.author.name} changed the channel name: {0.content}'.format(self)
if self.type is MessageType.channel_icon_change:
return '{0.author.name} changed the channel icon.'.format(self)
if self.type is MessageType.new_member:
formats = [
"{0} just joined the server - glhf!",
"{0} just joined. Everyone, look busy!",
"{0} just joined. Can I get a heal?",
"{0} joined your party.",
"{0} joined. You must construct additional pylons.",
"Ermagherd. {0} is here.",
"Welcome, {0}. Stay awhile and listen.",
"Welcome, {0}. We were expecting you ( ͡° ͜ʖ ͡°)",
"Welcome, {0}. We hope you brought pizza.",
"Welcome {0}. Leave your weapons by the door.",
"A wild {0} appeared.",
"Swoooosh. {0} just landed.",
"Brace yourselves. {0} just joined the server.",
"{0} just joined... or did they?",
"{0} just arrived. Seems OP - please nerf.",
"{0} just slid into the server.",
"A {0} has spawned in the server.",
"Big {0} showed up!",
"Where’s {0}? In the server!",
"{0} hopped into the server. Kangaroo!!",
"{0} just showed up. Hold my beer.",
"Challenger approaching - {0} has appeared!",
"It's a bird! It's a plane! Nevermind, it's just {0}.",
"It's {0}! Praise the sun! \\[T]/",
"Never gonna give {0} up. Never gonna let {0} down.",
"{0} has joined the battle bus.",
"Cheers, love! {0}'s here!",
"Hey! Listen! {0} has joined!",
"We've been expecting you {0}",
"It's dangerous to go alone, take {0}!",
"{0} has joined the server! It's super effective!",
"Cheers, love! {0} is here!",
"{0} is here, as the prophecy foretold.",
"{0} has arrived. Party's over.",
"Ready player {0}",
"{0} is here to kick butt and chew bubblegum. And {0} is all out of gum.",
"Hello. Is it {0} you're looking for?",
"{0} has joined. Stay a while and listen!",
"Roses are red, violets are blue, {0} joined this server with you",
]
# manually reconstruct the epoch with millisecond precision, because
# datetime.datetime.timestamp() doesn't return the exact posix
# timestamp with the precision that we need
created_at_ms = int((self.created_at - datetime.datetime(1970, 1, 1)).total_seconds() * 1000)
return formats[created_at_ms % len(formats)].format(self.author.name)
if self.type is MessageType.call:
# we're at the call message type now, which is a bit more complicated.
# we can make the assumption that Message.channel is a PrivateChannel
# with the type ChannelType.group or ChannelType.private
call_ended = self.call.ended_timestamp is not None
if self.channel.me in self.call.participants:
return '{0.author.name} started a call.'.format(self)
elif call_ended:
return 'You missed a call from {0.author.name}'.format(self)
else:
return '{0.author.name} started a call \N{EM DASH} Join the call.'.format(self)
|
python
|
def system_content(self):
r"""A property that returns the content that is rendered
regardless of the :attr:`Message.type`.
In the case of :attr:`MessageType.default`\, this just returns the
regular :attr:`Message.content`. Otherwise this returns an English
message denoting the contents of the system message.
"""
if self.type is MessageType.default:
return self.content
if self.type is MessageType.pins_add:
return '{0.name} pinned a message to this channel.'.format(self.author)
if self.type is MessageType.recipient_add:
return '{0.name} added {1.name} to the group.'.format(self.author, self.mentions[0])
if self.type is MessageType.recipient_remove:
return '{0.name} removed {1.name} from the group.'.format(self.author, self.mentions[0])
if self.type is MessageType.channel_name_change:
return '{0.author.name} changed the channel name: {0.content}'.format(self)
if self.type is MessageType.channel_icon_change:
return '{0.author.name} changed the channel icon.'.format(self)
if self.type is MessageType.new_member:
formats = [
"{0} just joined the server - glhf!",
"{0} just joined. Everyone, look busy!",
"{0} just joined. Can I get a heal?",
"{0} joined your party.",
"{0} joined. You must construct additional pylons.",
"Ermagherd. {0} is here.",
"Welcome, {0}. Stay awhile and listen.",
"Welcome, {0}. We were expecting you ( ͡° ͜ʖ ͡°)",
"Welcome, {0}. We hope you brought pizza.",
"Welcome {0}. Leave your weapons by the door.",
"A wild {0} appeared.",
"Swoooosh. {0} just landed.",
"Brace yourselves. {0} just joined the server.",
"{0} just joined... or did they?",
"{0} just arrived. Seems OP - please nerf.",
"{0} just slid into the server.",
"A {0} has spawned in the server.",
"Big {0} showed up!",
"Where’s {0}? In the server!",
"{0} hopped into the server. Kangaroo!!",
"{0} just showed up. Hold my beer.",
"Challenger approaching - {0} has appeared!",
"It's a bird! It's a plane! Nevermind, it's just {0}.",
"It's {0}! Praise the sun! \\[T]/",
"Never gonna give {0} up. Never gonna let {0} down.",
"{0} has joined the battle bus.",
"Cheers, love! {0}'s here!",
"Hey! Listen! {0} has joined!",
"We've been expecting you {0}",
"It's dangerous to go alone, take {0}!",
"{0} has joined the server! It's super effective!",
"Cheers, love! {0} is here!",
"{0} is here, as the prophecy foretold.",
"{0} has arrived. Party's over.",
"Ready player {0}",
"{0} is here to kick butt and chew bubblegum. And {0} is all out of gum.",
"Hello. Is it {0} you're looking for?",
"{0} has joined. Stay a while and listen!",
"Roses are red, violets are blue, {0} joined this server with you",
]
# manually reconstruct the epoch with millisecond precision, because
# datetime.datetime.timestamp() doesn't return the exact posix
# timestamp with the precision that we need
created_at_ms = int((self.created_at - datetime.datetime(1970, 1, 1)).total_seconds() * 1000)
return formats[created_at_ms % len(formats)].format(self.author.name)
if self.type is MessageType.call:
# we're at the call message type now, which is a bit more complicated.
# we can make the assumption that Message.channel is a PrivateChannel
# with the type ChannelType.group or ChannelType.private
call_ended = self.call.ended_timestamp is not None
if self.channel.me in self.call.participants:
return '{0.author.name} started a call.'.format(self)
elif call_ended:
return 'You missed a call from {0.author.name}'.format(self)
else:
return '{0.author.name} started a call \N{EM DASH} Join the call.'.format(self)
|
[
"def",
"system_content",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"is",
"MessageType",
".",
"default",
":",
"return",
"self",
".",
"content",
"if",
"self",
".",
"type",
"is",
"MessageType",
".",
"pins_add",
":",
"return",
"'{0.name} pinned a message to this channel.'",
".",
"format",
"(",
"self",
".",
"author",
")",
"if",
"self",
".",
"type",
"is",
"MessageType",
".",
"recipient_add",
":",
"return",
"'{0.name} added {1.name} to the group.'",
".",
"format",
"(",
"self",
".",
"author",
",",
"self",
".",
"mentions",
"[",
"0",
"]",
")",
"if",
"self",
".",
"type",
"is",
"MessageType",
".",
"recipient_remove",
":",
"return",
"'{0.name} removed {1.name} from the group.'",
".",
"format",
"(",
"self",
".",
"author",
",",
"self",
".",
"mentions",
"[",
"0",
"]",
")",
"if",
"self",
".",
"type",
"is",
"MessageType",
".",
"channel_name_change",
":",
"return",
"'{0.author.name} changed the channel name: {0.content}'",
".",
"format",
"(",
"self",
")",
"if",
"self",
".",
"type",
"is",
"MessageType",
".",
"channel_icon_change",
":",
"return",
"'{0.author.name} changed the channel icon.'",
".",
"format",
"(",
"self",
")",
"if",
"self",
".",
"type",
"is",
"MessageType",
".",
"new_member",
":",
"formats",
"=",
"[",
"\"{0} just joined the server - glhf!\"",
",",
"\"{0} just joined. Everyone, look busy!\"",
",",
"\"{0} just joined. Can I get a heal?\"",
",",
"\"{0} joined your party.\"",
",",
"\"{0} joined. You must construct additional pylons.\"",
",",
"\"Ermagherd. {0} is here.\"",
",",
"\"Welcome, {0}. Stay awhile and listen.\"",
",",
"\"Welcome, {0}. We were expecting you ( ͡° ͜ʖ ͡°)\",",
"",
"\"Welcome, {0}. We hope you brought pizza.\"",
",",
"\"Welcome {0}. Leave your weapons by the door.\"",
",",
"\"A wild {0} appeared.\"",
",",
"\"Swoooosh. {0} just landed.\"",
",",
"\"Brace yourselves. {0} just joined the server.\"",
",",
"\"{0} just joined... or did they?\"",
",",
"\"{0} just arrived. Seems OP - please nerf.\"",
",",
"\"{0} just slid into the server.\"",
",",
"\"A {0} has spawned in the server.\"",
",",
"\"Big {0} showed up!\"",
",",
"\"Where’s {0}? In the server!\",",
"",
"\"{0} hopped into the server. Kangaroo!!\"",
",",
"\"{0} just showed up. Hold my beer.\"",
",",
"\"Challenger approaching - {0} has appeared!\"",
",",
"\"It's a bird! It's a plane! Nevermind, it's just {0}.\"",
",",
"\"It's {0}! Praise the sun! \\\\[T]/\"",
",",
"\"Never gonna give {0} up. Never gonna let {0} down.\"",
",",
"\"{0} has joined the battle bus.\"",
",",
"\"Cheers, love! {0}'s here!\"",
",",
"\"Hey! Listen! {0} has joined!\"",
",",
"\"We've been expecting you {0}\"",
",",
"\"It's dangerous to go alone, take {0}!\"",
",",
"\"{0} has joined the server! It's super effective!\"",
",",
"\"Cheers, love! {0} is here!\"",
",",
"\"{0} is here, as the prophecy foretold.\"",
",",
"\"{0} has arrived. Party's over.\"",
",",
"\"Ready player {0}\"",
",",
"\"{0} is here to kick butt and chew bubblegum. And {0} is all out of gum.\"",
",",
"\"Hello. Is it {0} you're looking for?\"",
",",
"\"{0} has joined. Stay a while and listen!\"",
",",
"\"Roses are red, violets are blue, {0} joined this server with you\"",
",",
"]",
"# manually reconstruct the epoch with millisecond precision, because",
"# datetime.datetime.timestamp() doesn't return the exact posix",
"# timestamp with the precision that we need",
"created_at_ms",
"=",
"int",
"(",
"(",
"self",
".",
"created_at",
"-",
"datetime",
".",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
")",
".",
"total_seconds",
"(",
")",
"*",
"1000",
")",
"return",
"formats",
"[",
"created_at_ms",
"%",
"len",
"(",
"formats",
")",
"]",
".",
"format",
"(",
"self",
".",
"author",
".",
"name",
")",
"if",
"self",
".",
"type",
"is",
"MessageType",
".",
"call",
":",
"# we're at the call message type now, which is a bit more complicated.",
"# we can make the assumption that Message.channel is a PrivateChannel",
"# with the type ChannelType.group or ChannelType.private",
"call_ended",
"=",
"self",
".",
"call",
".",
"ended_timestamp",
"is",
"not",
"None",
"if",
"self",
".",
"channel",
".",
"me",
"in",
"self",
".",
"call",
".",
"participants",
":",
"return",
"'{0.author.name} started a call.'",
".",
"format",
"(",
"self",
")",
"elif",
"call_ended",
":",
"return",
"'You missed a call from {0.author.name}'",
".",
"format",
"(",
"self",
")",
"else",
":",
"return",
"'{0.author.name} started a call \\N{EM DASH} Join the call.'",
".",
"format",
"(",
"self",
")"
] |
r"""A property that returns the content that is rendered
regardless of the :attr:`Message.type`.
In the case of :attr:`MessageType.default`\, this just returns the
regular :attr:`Message.content`. Otherwise this returns an English
message denoting the contents of the system message.
|
[
"r",
"A",
"property",
"that",
"returns",
"the",
"content",
"that",
"is",
"rendered",
"regardless",
"of",
"the",
":",
"attr",
":",
"Message",
".",
"type",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L477-L564
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Message.delete
|
async def delete(self, *, delay=None):
"""|coro|
Deletes the message.
Your own messages could be deleted without any proper permissions. However to
delete other people's messages, you need the :attr:`~Permissions.manage_messages`
permission.
.. versionchanged:: 1.1.0
Added the new ``delay`` keyword-only parameter.
Parameters
-----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message.
Raises
------
Forbidden
You do not have proper permissions to delete the message.
HTTPException
Deleting the message failed.
"""
if delay is not None:
async def delete():
await asyncio.sleep(delay, loop=self._state.loop)
try:
await self._state.http.delete_message(self.channel.id, self.id)
except HTTPException:
pass
asyncio.ensure_future(delete(), loop=self._state.loop)
else:
await self._state.http.delete_message(self.channel.id, self.id)
|
python
|
async def delete(self, *, delay=None):
"""|coro|
Deletes the message.
Your own messages could be deleted without any proper permissions. However to
delete other people's messages, you need the :attr:`~Permissions.manage_messages`
permission.
.. versionchanged:: 1.1.0
Added the new ``delay`` keyword-only parameter.
Parameters
-----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message.
Raises
------
Forbidden
You do not have proper permissions to delete the message.
HTTPException
Deleting the message failed.
"""
if delay is not None:
async def delete():
await asyncio.sleep(delay, loop=self._state.loop)
try:
await self._state.http.delete_message(self.channel.id, self.id)
except HTTPException:
pass
asyncio.ensure_future(delete(), loop=self._state.loop)
else:
await self._state.http.delete_message(self.channel.id, self.id)
|
[
"async",
"def",
"delete",
"(",
"self",
",",
"*",
",",
"delay",
"=",
"None",
")",
":",
"if",
"delay",
"is",
"not",
"None",
":",
"async",
"def",
"delete",
"(",
")",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"delay",
",",
"loop",
"=",
"self",
".",
"_state",
".",
"loop",
")",
"try",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"delete_message",
"(",
"self",
".",
"channel",
".",
"id",
",",
"self",
".",
"id",
")",
"except",
"HTTPException",
":",
"pass",
"asyncio",
".",
"ensure_future",
"(",
"delete",
"(",
")",
",",
"loop",
"=",
"self",
".",
"_state",
".",
"loop",
")",
"else",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"delete_message",
"(",
"self",
".",
"channel",
".",
"id",
",",
"self",
".",
"id",
")"
] |
|coro|
Deletes the message.
Your own messages could be deleted without any proper permissions. However to
delete other people's messages, you need the :attr:`~Permissions.manage_messages`
permission.
.. versionchanged:: 1.1.0
Added the new ``delay`` keyword-only parameter.
Parameters
-----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message.
Raises
------
Forbidden
You do not have proper permissions to delete the message.
HTTPException
Deleting the message failed.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L566-L601
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Message.edit
|
async def edit(self, **fields):
"""|coro|
Edits the message.
The content must be able to be transformed into a string via ``str(content)``.
Parameters
-----------
content: Optional[:class:`str`]
The new content to replace the message with.
Could be ``None`` to remove the content.
embed: Optional[:class:`Embed`]
The new embed to replace the original with.
Could be ``None`` to remove the embed.
delete_after: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message we just edited. If the deletion fails,
then it is silently ignored.
Raises
-------
HTTPException
Editing the message failed.
"""
try:
content = fields['content']
except KeyError:
pass
else:
if content is not None:
fields['content'] = str(content)
try:
embed = fields['embed']
except KeyError:
pass
else:
if embed is not None:
fields['embed'] = embed.to_dict()
data = await self._state.http.edit_message(self.channel.id, self.id, **fields)
self._update(channel=self.channel, data=data)
try:
delete_after = fields['delete_after']
except KeyError:
pass
else:
if delete_after is not None:
await self.delete(delay=delete_after)
|
python
|
async def edit(self, **fields):
"""|coro|
Edits the message.
The content must be able to be transformed into a string via ``str(content)``.
Parameters
-----------
content: Optional[:class:`str`]
The new content to replace the message with.
Could be ``None`` to remove the content.
embed: Optional[:class:`Embed`]
The new embed to replace the original with.
Could be ``None`` to remove the embed.
delete_after: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message we just edited. If the deletion fails,
then it is silently ignored.
Raises
-------
HTTPException
Editing the message failed.
"""
try:
content = fields['content']
except KeyError:
pass
else:
if content is not None:
fields['content'] = str(content)
try:
embed = fields['embed']
except KeyError:
pass
else:
if embed is not None:
fields['embed'] = embed.to_dict()
data = await self._state.http.edit_message(self.channel.id, self.id, **fields)
self._update(channel=self.channel, data=data)
try:
delete_after = fields['delete_after']
except KeyError:
pass
else:
if delete_after is not None:
await self.delete(delay=delete_after)
|
[
"async",
"def",
"edit",
"(",
"self",
",",
"*",
"*",
"fields",
")",
":",
"try",
":",
"content",
"=",
"fields",
"[",
"'content'",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"content",
"is",
"not",
"None",
":",
"fields",
"[",
"'content'",
"]",
"=",
"str",
"(",
"content",
")",
"try",
":",
"embed",
"=",
"fields",
"[",
"'embed'",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"embed",
"is",
"not",
"None",
":",
"fields",
"[",
"'embed'",
"]",
"=",
"embed",
".",
"to_dict",
"(",
")",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"edit_message",
"(",
"self",
".",
"channel",
".",
"id",
",",
"self",
".",
"id",
",",
"*",
"*",
"fields",
")",
"self",
".",
"_update",
"(",
"channel",
"=",
"self",
".",
"channel",
",",
"data",
"=",
"data",
")",
"try",
":",
"delete_after",
"=",
"fields",
"[",
"'delete_after'",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"delete_after",
"is",
"not",
"None",
":",
"await",
"self",
".",
"delete",
"(",
"delay",
"=",
"delete_after",
")"
] |
|coro|
Edits the message.
The content must be able to be transformed into a string via ``str(content)``.
Parameters
-----------
content: Optional[:class:`str`]
The new content to replace the message with.
Could be ``None`` to remove the content.
embed: Optional[:class:`Embed`]
The new embed to replace the original with.
Could be ``None`` to remove the embed.
delete_after: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message we just edited. If the deletion fails,
then it is silently ignored.
Raises
-------
HTTPException
Editing the message failed.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L603-L654
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Message.pin
|
async def pin(self):
"""|coro|
Pins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Raises
-------
Forbidden
You do not have permissions to pin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Pinning the message failed, probably due to the channel
having more than 50 pinned messages.
"""
await self._state.http.pin_message(self.channel.id, self.id)
self.pinned = True
|
python
|
async def pin(self):
"""|coro|
Pins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Raises
-------
Forbidden
You do not have permissions to pin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Pinning the message failed, probably due to the channel
having more than 50 pinned messages.
"""
await self._state.http.pin_message(self.channel.id, self.id)
self.pinned = True
|
[
"async",
"def",
"pin",
"(",
"self",
")",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"pin_message",
"(",
"self",
".",
"channel",
".",
"id",
",",
"self",
".",
"id",
")",
"self",
".",
"pinned",
"=",
"True"
] |
|coro|
Pins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Raises
-------
Forbidden
You do not have permissions to pin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Pinning the message failed, probably due to the channel
having more than 50 pinned messages.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L656-L676
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Message.unpin
|
async def unpin(self):
"""|coro|
Unpins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Raises
-------
Forbidden
You do not have permissions to unpin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Unpinning the message failed.
"""
await self._state.http.unpin_message(self.channel.id, self.id)
self.pinned = False
|
python
|
async def unpin(self):
"""|coro|
Unpins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Raises
-------
Forbidden
You do not have permissions to unpin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Unpinning the message failed.
"""
await self._state.http.unpin_message(self.channel.id, self.id)
self.pinned = False
|
[
"async",
"def",
"unpin",
"(",
"self",
")",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"unpin_message",
"(",
"self",
".",
"channel",
".",
"id",
",",
"self",
".",
"id",
")",
"self",
".",
"pinned",
"=",
"False"
] |
|coro|
Unpins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Raises
-------
Forbidden
You do not have permissions to unpin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Unpinning the message failed.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L678-L697
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Message.add_reaction
|
async def add_reaction(self, emoji):
"""|coro|
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You must have the :attr:`~Permissions.read_message_history` permission
to use this. If nobody else has reacted to the message using this
emoji, the :attr:`~Permissions.add_reactions` permission is required.
Parameters
------------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to react with.
Raises
--------
HTTPException
Adding the reaction failed.
Forbidden
You do not have the proper permissions to react to the message.
NotFound
The emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = self._emoji_reaction(emoji)
await self._state.http.add_reaction(self.channel.id, self.id, emoji)
|
python
|
async def add_reaction(self, emoji):
"""|coro|
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You must have the :attr:`~Permissions.read_message_history` permission
to use this. If nobody else has reacted to the message using this
emoji, the :attr:`~Permissions.add_reactions` permission is required.
Parameters
------------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to react with.
Raises
--------
HTTPException
Adding the reaction failed.
Forbidden
You do not have the proper permissions to react to the message.
NotFound
The emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = self._emoji_reaction(emoji)
await self._state.http.add_reaction(self.channel.id, self.id, emoji)
|
[
"async",
"def",
"add_reaction",
"(",
"self",
",",
"emoji",
")",
":",
"emoji",
"=",
"self",
".",
"_emoji_reaction",
"(",
"emoji",
")",
"await",
"self",
".",
"_state",
".",
"http",
".",
"add_reaction",
"(",
"self",
".",
"channel",
".",
"id",
",",
"self",
".",
"id",
",",
"emoji",
")"
] |
|coro|
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You must have the :attr:`~Permissions.read_message_history` permission
to use this. If nobody else has reacted to the message using this
emoji, the :attr:`~Permissions.add_reactions` permission is required.
Parameters
------------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to react with.
Raises
--------
HTTPException
Adding the reaction failed.
Forbidden
You do not have the proper permissions to react to the message.
NotFound
The emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L699-L728
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Message.remove_reaction
|
async def remove_reaction(self, emoji, member):
"""|coro|
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
If the reaction is not your own (i.e. ``member`` parameter is not you) then
the :attr:`~Permissions.manage_messages` permission is needed.
The ``member`` parameter must represent a member and meet
the :class:`abc.Snowflake` abc.
Parameters
------------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to remove.
member: :class:`abc.Snowflake`
The member for which to remove the reaction.
Raises
--------
HTTPException
Removing the reaction failed.
Forbidden
You do not have the proper permissions to remove the reaction.
NotFound
The member or emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = self._emoji_reaction(emoji)
if member.id == self._state.self_id:
await self._state.http.remove_own_reaction(self.channel.id, self.id, emoji)
else:
await self._state.http.remove_reaction(self.channel.id, self.id, emoji, member.id)
|
python
|
async def remove_reaction(self, emoji, member):
"""|coro|
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
If the reaction is not your own (i.e. ``member`` parameter is not you) then
the :attr:`~Permissions.manage_messages` permission is needed.
The ``member`` parameter must represent a member and meet
the :class:`abc.Snowflake` abc.
Parameters
------------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to remove.
member: :class:`abc.Snowflake`
The member for which to remove the reaction.
Raises
--------
HTTPException
Removing the reaction failed.
Forbidden
You do not have the proper permissions to remove the reaction.
NotFound
The member or emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = self._emoji_reaction(emoji)
if member.id == self._state.self_id:
await self._state.http.remove_own_reaction(self.channel.id, self.id, emoji)
else:
await self._state.http.remove_reaction(self.channel.id, self.id, emoji, member.id)
|
[
"async",
"def",
"remove_reaction",
"(",
"self",
",",
"emoji",
",",
"member",
")",
":",
"emoji",
"=",
"self",
".",
"_emoji_reaction",
"(",
"emoji",
")",
"if",
"member",
".",
"id",
"==",
"self",
".",
"_state",
".",
"self_id",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"remove_own_reaction",
"(",
"self",
".",
"channel",
".",
"id",
",",
"self",
".",
"id",
",",
"emoji",
")",
"else",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"remove_reaction",
"(",
"self",
".",
"channel",
".",
"id",
",",
"self",
".",
"id",
",",
"emoji",
",",
"member",
".",
"id",
")"
] |
|coro|
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
If the reaction is not your own (i.e. ``member`` parameter is not you) then
the :attr:`~Permissions.manage_messages` permission is needed.
The ``member`` parameter must represent a member and meet
the :class:`abc.Snowflake` abc.
Parameters
------------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to remove.
member: :class:`abc.Snowflake`
The member for which to remove the reaction.
Raises
--------
HTTPException
Removing the reaction failed.
Forbidden
You do not have the proper permissions to remove the reaction.
NotFound
The member or emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L730-L767
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Message.clear_reactions
|
async def clear_reactions(self):
"""|coro|
Removes all the reactions from the message.
You need the :attr:`~Permissions.manage_messages` permission to use this.
Raises
--------
HTTPException
Removing the reactions failed.
Forbidden
You do not have the proper permissions to remove all the reactions.
"""
await self._state.http.clear_reactions(self.channel.id, self.id)
|
python
|
async def clear_reactions(self):
"""|coro|
Removes all the reactions from the message.
You need the :attr:`~Permissions.manage_messages` permission to use this.
Raises
--------
HTTPException
Removing the reactions failed.
Forbidden
You do not have the proper permissions to remove all the reactions.
"""
await self._state.http.clear_reactions(self.channel.id, self.id)
|
[
"async",
"def",
"clear_reactions",
"(",
"self",
")",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"clear_reactions",
"(",
"self",
".",
"channel",
".",
"id",
",",
"self",
".",
"id",
")"
] |
|coro|
Removes all the reactions from the message.
You need the :attr:`~Permissions.manage_messages` permission to use this.
Raises
--------
HTTPException
Removing the reactions failed.
Forbidden
You do not have the proper permissions to remove all the reactions.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L785-L799
|
train
|
Rapptz/discord.py
|
discord/message.py
|
Message.ack
|
async def ack(self):
"""|coro|
Marks this message as read.
The user must not be a bot user.
Raises
-------
HTTPException
Acking failed.
ClientException
You must not be a bot user.
"""
state = self._state
if state.is_bot:
raise ClientException('Must not be a bot account to ack messages.')
return await state.http.ack_message(self.channel.id, self.id)
|
python
|
async def ack(self):
"""|coro|
Marks this message as read.
The user must not be a bot user.
Raises
-------
HTTPException
Acking failed.
ClientException
You must not be a bot user.
"""
state = self._state
if state.is_bot:
raise ClientException('Must not be a bot account to ack messages.')
return await state.http.ack_message(self.channel.id, self.id)
|
[
"async",
"def",
"ack",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"_state",
"if",
"state",
".",
"is_bot",
":",
"raise",
"ClientException",
"(",
"'Must not be a bot account to ack messages.'",
")",
"return",
"await",
"state",
".",
"http",
".",
"ack_message",
"(",
"self",
".",
"channel",
".",
"id",
",",
"self",
".",
"id",
")"
] |
|coro|
Marks this message as read.
The user must not be a bot user.
Raises
-------
HTTPException
Acking failed.
ClientException
You must not be a bot user.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L801-L819
|
train
|
Rapptz/discord.py
|
discord/activity.py
|
Activity.large_image_url
|
def large_image_url(self):
"""Optional[:class:`str`]: Returns a URL pointing to the large image asset of this activity if applicable."""
if self.application_id is None:
return None
try:
large_image = self.assets['large_image']
except KeyError:
return None
else:
return 'https://cdn.discordapp.com/app-assets/{0}/{1}.png'.format(self.application_id, large_image)
|
python
|
def large_image_url(self):
"""Optional[:class:`str`]: Returns a URL pointing to the large image asset of this activity if applicable."""
if self.application_id is None:
return None
try:
large_image = self.assets['large_image']
except KeyError:
return None
else:
return 'https://cdn.discordapp.com/app-assets/{0}/{1}.png'.format(self.application_id, large_image)
|
[
"def",
"large_image_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"application_id",
"is",
"None",
":",
"return",
"None",
"try",
":",
"large_image",
"=",
"self",
".",
"assets",
"[",
"'large_image'",
"]",
"except",
"KeyError",
":",
"return",
"None",
"else",
":",
"return",
"'https://cdn.discordapp.com/app-assets/{0}/{1}.png'",
".",
"format",
"(",
"self",
".",
"application_id",
",",
"large_image",
")"
] |
Optional[:class:`str`]: Returns a URL pointing to the large image asset of this activity if applicable.
|
[
"Optional",
"[",
":",
"class",
":",
"str",
"]",
":",
"Returns",
"a",
"URL",
"pointing",
"to",
"the",
"large",
"image",
"asset",
"of",
"this",
"activity",
"if",
"applicable",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/activity.py#L186-L196
|
train
|
Rapptz/discord.py
|
discord/activity.py
|
Activity.small_image_url
|
def small_image_url(self):
"""Optional[:class:`str`]: Returns a URL pointing to the small image asset of this activity if applicable."""
if self.application_id is None:
return None
try:
small_image = self.assets['small_image']
except KeyError:
return None
else:
return 'https://cdn.discordapp.com/app-assets/{0}/{1}.png'.format(self.application_id, small_image)
|
python
|
def small_image_url(self):
"""Optional[:class:`str`]: Returns a URL pointing to the small image asset of this activity if applicable."""
if self.application_id is None:
return None
try:
small_image = self.assets['small_image']
except KeyError:
return None
else:
return 'https://cdn.discordapp.com/app-assets/{0}/{1}.png'.format(self.application_id, small_image)
|
[
"def",
"small_image_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"application_id",
"is",
"None",
":",
"return",
"None",
"try",
":",
"small_image",
"=",
"self",
".",
"assets",
"[",
"'small_image'",
"]",
"except",
"KeyError",
":",
"return",
"None",
"else",
":",
"return",
"'https://cdn.discordapp.com/app-assets/{0}/{1}.png'",
".",
"format",
"(",
"self",
".",
"application_id",
",",
"small_image",
")"
] |
Optional[:class:`str`]: Returns a URL pointing to the small image asset of this activity if applicable.
|
[
"Optional",
"[",
":",
"class",
":",
"str",
"]",
":",
"Returns",
"a",
"URL",
"pointing",
"to",
"the",
"small",
"image",
"asset",
"of",
"this",
"activity",
"if",
"applicable",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/activity.py#L199-L209
|
train
|
Rapptz/discord.py
|
discord/activity.py
|
Spotify.album_cover_url
|
def album_cover_url(self):
""":class:`str`: The album cover image URL from Spotify's CDN."""
large_image = self._assets.get('large_image', '')
if large_image[:8] != 'spotify:':
return ''
album_image_id = large_image[8:]
return 'https://i.scdn.co/image/' + album_image_id
|
python
|
def album_cover_url(self):
""":class:`str`: The album cover image URL from Spotify's CDN."""
large_image = self._assets.get('large_image', '')
if large_image[:8] != 'spotify:':
return ''
album_image_id = large_image[8:]
return 'https://i.scdn.co/image/' + album_image_id
|
[
"def",
"album_cover_url",
"(",
"self",
")",
":",
"large_image",
"=",
"self",
".",
"_assets",
".",
"get",
"(",
"'large_image'",
",",
"''",
")",
"if",
"large_image",
"[",
":",
"8",
"]",
"!=",
"'spotify:'",
":",
"return",
"''",
"album_image_id",
"=",
"large_image",
"[",
"8",
":",
"]",
"return",
"'https://i.scdn.co/image/'",
"+",
"album_image_id"
] |
:class:`str`: The album cover image URL from Spotify's CDN.
|
[
":",
"class",
":",
"str",
":",
"The",
"album",
"cover",
"image",
"URL",
"from",
"Spotify",
"s",
"CDN",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/activity.py#L539-L545
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
when_mentioned_or
|
def when_mentioned_or(*prefixes):
"""A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the :attr:`.Bot.command_prefix` attribute.
Example
--------
.. code-block:: python3
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
.. note::
This callable returns another callable, so if this is done inside a custom
callable, you must call the returned callable, for example:
.. code-block:: python3
async def get_prefix(bot, message):
extras = await prefixes_for(message.guild) # returns a list
return commands.when_mentioned_or(*extras)(bot, message)
See Also
----------
:func:`.when_mentioned`
"""
def inner(bot, msg):
r = list(prefixes)
r = when_mentioned(bot, msg) + r
return r
return inner
|
python
|
def when_mentioned_or(*prefixes):
"""A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the :attr:`.Bot.command_prefix` attribute.
Example
--------
.. code-block:: python3
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
.. note::
This callable returns another callable, so if this is done inside a custom
callable, you must call the returned callable, for example:
.. code-block:: python3
async def get_prefix(bot, message):
extras = await prefixes_for(message.guild) # returns a list
return commands.when_mentioned_or(*extras)(bot, message)
See Also
----------
:func:`.when_mentioned`
"""
def inner(bot, msg):
r = list(prefixes)
r = when_mentioned(bot, msg) + r
return r
return inner
|
[
"def",
"when_mentioned_or",
"(",
"*",
"prefixes",
")",
":",
"def",
"inner",
"(",
"bot",
",",
"msg",
")",
":",
"r",
"=",
"list",
"(",
"prefixes",
")",
"r",
"=",
"when_mentioned",
"(",
"bot",
",",
"msg",
")",
"+",
"r",
"return",
"r",
"return",
"inner"
] |
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the :attr:`.Bot.command_prefix` attribute.
Example
--------
.. code-block:: python3
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
.. note::
This callable returns another callable, so if this is done inside a custom
callable, you must call the returned callable, for example:
.. code-block:: python3
async def get_prefix(bot, message):
extras = await prefixes_for(message.guild) # returns a list
return commands.when_mentioned_or(*extras)(bot, message)
See Also
----------
:func:`.when_mentioned`
|
[
"A",
"callable",
"that",
"implements",
"when",
"mentioned",
"or",
"other",
"prefixes",
"provided",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L52-L86
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.on_command_error
|
async def on_command_error(self, context, exception):
"""|coro|
The default command error handler provided by the bot.
By default this prints to ``sys.stderr`` however it could be
overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
"""
if self.extra_events.get('on_command_error', None):
return
if hasattr(context.command, 'on_error'):
return
cog = context.cog
if cog:
if Cog._get_overridden_method(cog.cog_command_error) is not None:
return
print('Ignoring exception in command {}:'.format(context.command), file=sys.stderr)
traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)
|
python
|
async def on_command_error(self, context, exception):
"""|coro|
The default command error handler provided by the bot.
By default this prints to ``sys.stderr`` however it could be
overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
"""
if self.extra_events.get('on_command_error', None):
return
if hasattr(context.command, 'on_error'):
return
cog = context.cog
if cog:
if Cog._get_overridden_method(cog.cog_command_error) is not None:
return
print('Ignoring exception in command {}:'.format(context.command), file=sys.stderr)
traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)
|
[
"async",
"def",
"on_command_error",
"(",
"self",
",",
"context",
",",
"exception",
")",
":",
"if",
"self",
".",
"extra_events",
".",
"get",
"(",
"'on_command_error'",
",",
"None",
")",
":",
"return",
"if",
"hasattr",
"(",
"context",
".",
"command",
",",
"'on_error'",
")",
":",
"return",
"cog",
"=",
"context",
".",
"cog",
"if",
"cog",
":",
"if",
"Cog",
".",
"_get_overridden_method",
"(",
"cog",
".",
"cog_command_error",
")",
"is",
"not",
"None",
":",
"return",
"print",
"(",
"'Ignoring exception in command {}:'",
".",
"format",
"(",
"context",
".",
"command",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"traceback",
".",
"print_exception",
"(",
"type",
"(",
"exception",
")",
",",
"exception",
",",
"exception",
".",
"__traceback__",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] |
|coro|
The default command error handler provided by the bot.
By default this prints to ``sys.stderr`` however it could be
overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L146-L168
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.add_check
|
def add_check(self, func, *, call_once=False):
"""Adds a global check to the bot.
This is the non-decorator interface to :meth:`.check`
and :meth:`.check_once`.
Parameters
-----------
func
The function that was used as a global check.
call_once: :class:`bool`
If the function should only be called once per
:meth:`.Command.invoke` call.
"""
if call_once:
self._check_once.append(func)
else:
self._checks.append(func)
|
python
|
def add_check(self, func, *, call_once=False):
"""Adds a global check to the bot.
This is the non-decorator interface to :meth:`.check`
and :meth:`.check_once`.
Parameters
-----------
func
The function that was used as a global check.
call_once: :class:`bool`
If the function should only be called once per
:meth:`.Command.invoke` call.
"""
if call_once:
self._check_once.append(func)
else:
self._checks.append(func)
|
[
"def",
"add_check",
"(",
"self",
",",
"func",
",",
"*",
",",
"call_once",
"=",
"False",
")",
":",
"if",
"call_once",
":",
"self",
".",
"_check_once",
".",
"append",
"(",
"func",
")",
"else",
":",
"self",
".",
"_checks",
".",
"append",
"(",
"func",
")"
] |
Adds a global check to the bot.
This is the non-decorator interface to :meth:`.check`
and :meth:`.check_once`.
Parameters
-----------
func
The function that was used as a global check.
call_once: :class:`bool`
If the function should only be called once per
:meth:`.Command.invoke` call.
|
[
"Adds",
"a",
"global",
"check",
"to",
"the",
"bot",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L200-L218
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.remove_check
|
def remove_check(self, func, *, call_once=False):
"""Removes a global check from the bot.
This function is idempotent and will not raise an exception
if the function is not in the global checks.
Parameters
-----------
func
The function to remove from the global checks.
call_once: :class:`bool`
If the function was added with ``call_once=True`` in
the :meth:`.Bot.add_check` call or using :meth:`.check_once`.
"""
l = self._check_once if call_once else self._checks
try:
l.remove(func)
except ValueError:
pass
|
python
|
def remove_check(self, func, *, call_once=False):
"""Removes a global check from the bot.
This function is idempotent and will not raise an exception
if the function is not in the global checks.
Parameters
-----------
func
The function to remove from the global checks.
call_once: :class:`bool`
If the function was added with ``call_once=True`` in
the :meth:`.Bot.add_check` call or using :meth:`.check_once`.
"""
l = self._check_once if call_once else self._checks
try:
l.remove(func)
except ValueError:
pass
|
[
"def",
"remove_check",
"(",
"self",
",",
"func",
",",
"*",
",",
"call_once",
"=",
"False",
")",
":",
"l",
"=",
"self",
".",
"_check_once",
"if",
"call_once",
"else",
"self",
".",
"_checks",
"try",
":",
"l",
".",
"remove",
"(",
"func",
")",
"except",
"ValueError",
":",
"pass"
] |
Removes a global check from the bot.
This function is idempotent and will not raise an exception
if the function is not in the global checks.
Parameters
-----------
func
The function to remove from the global checks.
call_once: :class:`bool`
If the function was added with ``call_once=True`` in
the :meth:`.Bot.add_check` call or using :meth:`.check_once`.
|
[
"Removes",
"a",
"global",
"check",
"from",
"the",
"bot",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L220-L239
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.is_owner
|
async def is_owner(self, user):
"""Checks if a :class:`~discord.User` or :class:`~discord.Member` is the owner of
this bot.
If an :attr:`owner_id` is not set, it is fetched automatically
through the use of :meth:`~.Bot.application_info`.
Parameters
-----------
user: :class:`.abc.User`
The user to check for.
"""
if self.owner_id is None:
app = await self.application_info()
self.owner_id = owner_id = app.owner.id
return user.id == owner_id
return user.id == self.owner_id
|
python
|
async def is_owner(self, user):
"""Checks if a :class:`~discord.User` or :class:`~discord.Member` is the owner of
this bot.
If an :attr:`owner_id` is not set, it is fetched automatically
through the use of :meth:`~.Bot.application_info`.
Parameters
-----------
user: :class:`.abc.User`
The user to check for.
"""
if self.owner_id is None:
app = await self.application_info()
self.owner_id = owner_id = app.owner.id
return user.id == owner_id
return user.id == self.owner_id
|
[
"async",
"def",
"is_owner",
"(",
"self",
",",
"user",
")",
":",
"if",
"self",
".",
"owner_id",
"is",
"None",
":",
"app",
"=",
"await",
"self",
".",
"application_info",
"(",
")",
"self",
".",
"owner_id",
"=",
"owner_id",
"=",
"app",
".",
"owner",
".",
"id",
"return",
"user",
".",
"id",
"==",
"owner_id",
"return",
"user",
".",
"id",
"==",
"self",
".",
"owner_id"
] |
Checks if a :class:`~discord.User` or :class:`~discord.Member` is the owner of
this bot.
If an :attr:`owner_id` is not set, it is fetched automatically
through the use of :meth:`~.Bot.application_info`.
Parameters
-----------
user: :class:`.abc.User`
The user to check for.
|
[
"Checks",
"if",
"a",
":",
"class",
":",
"~discord",
".",
"User",
"or",
":",
"class",
":",
"~discord",
".",
"Member",
"is",
"the",
"owner",
"of",
"this",
"bot",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L281-L298
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.add_listener
|
def add_listener(self, func, name=None):
"""The non decorator alternative to :meth:`.listen`.
Parameters
-----------
func: :ref:`coroutine <coroutine>`
The function to call.
name: Optional[:class:`str`]
The name of the event to listen for. Defaults to ``func.__name__``.
Example
--------
.. code-block:: python3
async def on_ready(): pass
async def my_message(message): pass
bot.add_listener(on_ready)
bot.add_listener(my_message, 'on_message')
"""
name = func.__name__ if name is None else name
if not asyncio.iscoroutinefunction(func):
raise TypeError('Listeners must be coroutines')
if name in self.extra_events:
self.extra_events[name].append(func)
else:
self.extra_events[name] = [func]
|
python
|
def add_listener(self, func, name=None):
"""The non decorator alternative to :meth:`.listen`.
Parameters
-----------
func: :ref:`coroutine <coroutine>`
The function to call.
name: Optional[:class:`str`]
The name of the event to listen for. Defaults to ``func.__name__``.
Example
--------
.. code-block:: python3
async def on_ready(): pass
async def my_message(message): pass
bot.add_listener(on_ready)
bot.add_listener(my_message, 'on_message')
"""
name = func.__name__ if name is None else name
if not asyncio.iscoroutinefunction(func):
raise TypeError('Listeners must be coroutines')
if name in self.extra_events:
self.extra_events[name].append(func)
else:
self.extra_events[name] = [func]
|
[
"def",
"add_listener",
"(",
"self",
",",
"func",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"func",
".",
"__name__",
"if",
"name",
"is",
"None",
"else",
"name",
"if",
"not",
"asyncio",
".",
"iscoroutinefunction",
"(",
"func",
")",
":",
"raise",
"TypeError",
"(",
"'Listeners must be coroutines'",
")",
"if",
"name",
"in",
"self",
".",
"extra_events",
":",
"self",
".",
"extra_events",
"[",
"name",
"]",
".",
"append",
"(",
"func",
")",
"else",
":",
"self",
".",
"extra_events",
"[",
"name",
"]",
"=",
"[",
"func",
"]"
] |
The non decorator alternative to :meth:`.listen`.
Parameters
-----------
func: :ref:`coroutine <coroutine>`
The function to call.
name: Optional[:class:`str`]
The name of the event to listen for. Defaults to ``func.__name__``.
Example
--------
.. code-block:: python3
async def on_ready(): pass
async def my_message(message): pass
bot.add_listener(on_ready)
bot.add_listener(my_message, 'on_message')
|
[
"The",
"non",
"decorator",
"alternative",
"to",
":",
"meth",
":",
".",
"listen",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L367-L397
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.remove_listener
|
def remove_listener(self, func, name=None):
"""Removes a listener from the pool of listeners.
Parameters
-----------
func
The function that was used as a listener to remove.
name: :class:`str`
The name of the event we want to remove. Defaults to
``func.__name__``.
"""
name = func.__name__ if name is None else name
if name in self.extra_events:
try:
self.extra_events[name].remove(func)
except ValueError:
pass
|
python
|
def remove_listener(self, func, name=None):
"""Removes a listener from the pool of listeners.
Parameters
-----------
func
The function that was used as a listener to remove.
name: :class:`str`
The name of the event we want to remove. Defaults to
``func.__name__``.
"""
name = func.__name__ if name is None else name
if name in self.extra_events:
try:
self.extra_events[name].remove(func)
except ValueError:
pass
|
[
"def",
"remove_listener",
"(",
"self",
",",
"func",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"func",
".",
"__name__",
"if",
"name",
"is",
"None",
"else",
"name",
"if",
"name",
"in",
"self",
".",
"extra_events",
":",
"try",
":",
"self",
".",
"extra_events",
"[",
"name",
"]",
".",
"remove",
"(",
"func",
")",
"except",
"ValueError",
":",
"pass"
] |
Removes a listener from the pool of listeners.
Parameters
-----------
func
The function that was used as a listener to remove.
name: :class:`str`
The name of the event we want to remove. Defaults to
``func.__name__``.
|
[
"Removes",
"a",
"listener",
"from",
"the",
"pool",
"of",
"listeners",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L399-L417
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.listen
|
def listen(self, name=None):
"""A decorator that registers another function as an external
event listener. Basically this allows you to listen to multiple
events from different places e.g. such as :func:`.on_ready`
The functions being listened to must be a coroutine.
Example
--------
.. code-block:: python3
@bot.listen()
async def on_message(message):
print('one')
# in some other file...
@bot.listen('on_message')
async def my_message(message):
print('two')
Would print one and two in an unspecified order.
Raises
-------
TypeError
The function being listened to is not a coroutine.
"""
def decorator(func):
self.add_listener(func, name)
return func
return decorator
|
python
|
def listen(self, name=None):
"""A decorator that registers another function as an external
event listener. Basically this allows you to listen to multiple
events from different places e.g. such as :func:`.on_ready`
The functions being listened to must be a coroutine.
Example
--------
.. code-block:: python3
@bot.listen()
async def on_message(message):
print('one')
# in some other file...
@bot.listen('on_message')
async def my_message(message):
print('two')
Would print one and two in an unspecified order.
Raises
-------
TypeError
The function being listened to is not a coroutine.
"""
def decorator(func):
self.add_listener(func, name)
return func
return decorator
|
[
"def",
"listen",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"self",
".",
"add_listener",
"(",
"func",
",",
"name",
")",
"return",
"func",
"return",
"decorator"
] |
A decorator that registers another function as an external
event listener. Basically this allows you to listen to multiple
events from different places e.g. such as :func:`.on_ready`
The functions being listened to must be a coroutine.
Example
--------
.. code-block:: python3
@bot.listen()
async def on_message(message):
print('one')
# in some other file...
@bot.listen('on_message')
async def my_message(message):
print('two')
Would print one and two in an unspecified order.
Raises
-------
TypeError
The function being listened to is not a coroutine.
|
[
"A",
"decorator",
"that",
"registers",
"another",
"function",
"as",
"an",
"external",
"event",
"listener",
".",
"Basically",
"this",
"allows",
"you",
"to",
"listen",
"to",
"multiple",
"events",
"from",
"different",
"places",
"e",
".",
"g",
".",
"such",
"as",
":",
"func",
":",
".",
"on_ready"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L419-L453
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.add_cog
|
def add_cog(self, cog):
"""Adds a "cog" to the bot.
A cog is a class that has its own event listeners and commands.
Parameters
-----------
cog: :class:`.Cog`
The cog to register to the bot.
Raises
-------
TypeError
The cog does not inherit from :class:`.Cog`.
CommandError
An error happened during loading.
"""
if not isinstance(cog, Cog):
raise TypeError('cogs must derive from Cog')
cog = cog._inject(self)
self.__cogs[cog.__cog_name__] = cog
|
python
|
def add_cog(self, cog):
"""Adds a "cog" to the bot.
A cog is a class that has its own event listeners and commands.
Parameters
-----------
cog: :class:`.Cog`
The cog to register to the bot.
Raises
-------
TypeError
The cog does not inherit from :class:`.Cog`.
CommandError
An error happened during loading.
"""
if not isinstance(cog, Cog):
raise TypeError('cogs must derive from Cog')
cog = cog._inject(self)
self.__cogs[cog.__cog_name__] = cog
|
[
"def",
"add_cog",
"(",
"self",
",",
"cog",
")",
":",
"if",
"not",
"isinstance",
"(",
"cog",
",",
"Cog",
")",
":",
"raise",
"TypeError",
"(",
"'cogs must derive from Cog'",
")",
"cog",
"=",
"cog",
".",
"_inject",
"(",
"self",
")",
"self",
".",
"__cogs",
"[",
"cog",
".",
"__cog_name__",
"]",
"=",
"cog"
] |
Adds a "cog" to the bot.
A cog is a class that has its own event listeners and commands.
Parameters
-----------
cog: :class:`.Cog`
The cog to register to the bot.
Raises
-------
TypeError
The cog does not inherit from :class:`.Cog`.
CommandError
An error happened during loading.
|
[
"Adds",
"a",
"cog",
"to",
"the",
"bot",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L457-L479
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.remove_cog
|
def remove_cog(self, name):
"""Removes a cog from the bot.
All registered commands and event listeners that the
cog has registered will be removed as well.
If no cog is found then this method has no effect.
Parameters
-----------
name: :class:`str`
The name of the cog to remove.
"""
cog = self.__cogs.pop(name, None)
if cog is None:
return
help_command = self._help_command
if help_command and help_command.cog is cog:
help_command.cog = None
cog._eject(self)
|
python
|
def remove_cog(self, name):
"""Removes a cog from the bot.
All registered commands and event listeners that the
cog has registered will be removed as well.
If no cog is found then this method has no effect.
Parameters
-----------
name: :class:`str`
The name of the cog to remove.
"""
cog = self.__cogs.pop(name, None)
if cog is None:
return
help_command = self._help_command
if help_command and help_command.cog is cog:
help_command.cog = None
cog._eject(self)
|
[
"def",
"remove_cog",
"(",
"self",
",",
"name",
")",
":",
"cog",
"=",
"self",
".",
"__cogs",
".",
"pop",
"(",
"name",
",",
"None",
")",
"if",
"cog",
"is",
"None",
":",
"return",
"help_command",
"=",
"self",
".",
"_help_command",
"if",
"help_command",
"and",
"help_command",
".",
"cog",
"is",
"cog",
":",
"help_command",
".",
"cog",
"=",
"None",
"cog",
".",
"_eject",
"(",
"self",
")"
] |
Removes a cog from the bot.
All registered commands and event listeners that the
cog has registered will be removed as well.
If no cog is found then this method has no effect.
Parameters
-----------
name: :class:`str`
The name of the cog to remove.
|
[
"Removes",
"a",
"cog",
"from",
"the",
"bot",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L495-L516
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.load_extension
|
def load_extension(self, name):
"""Loads an extension.
An extension is a python module that contains commands, cogs, or
listeners.
An extension must have a global function, ``setup`` defined as
the entry point on what to do when the extension is loaded. This entry
point must have a single argument, the ``bot``.
Parameters
------------
name: :class:`str`
The extension name to load. It must be dot separated like
regular Python imports if accessing a sub-module. e.g.
``foo.test`` if you want to import ``foo/test.py``.
Raises
--------
ExtensionNotFound
The extension could not be imported.
ExtensionAlreadyLoaded
The extension is already loaded.
NoEntryPointError
The extension does not have a setup function.
ExtensionFailed
The extension setup function had an execution error.
"""
if name in self.__extensions:
raise errors.ExtensionAlreadyLoaded(name)
try:
lib = importlib.import_module(name)
except ImportError as e:
raise errors.ExtensionNotFound(name, e) from e
else:
self._load_from_module_spec(lib, name)
|
python
|
def load_extension(self, name):
"""Loads an extension.
An extension is a python module that contains commands, cogs, or
listeners.
An extension must have a global function, ``setup`` defined as
the entry point on what to do when the extension is loaded. This entry
point must have a single argument, the ``bot``.
Parameters
------------
name: :class:`str`
The extension name to load. It must be dot separated like
regular Python imports if accessing a sub-module. e.g.
``foo.test`` if you want to import ``foo/test.py``.
Raises
--------
ExtensionNotFound
The extension could not be imported.
ExtensionAlreadyLoaded
The extension is already loaded.
NoEntryPointError
The extension does not have a setup function.
ExtensionFailed
The extension setup function had an execution error.
"""
if name in self.__extensions:
raise errors.ExtensionAlreadyLoaded(name)
try:
lib = importlib.import_module(name)
except ImportError as e:
raise errors.ExtensionNotFound(name, e) from e
else:
self._load_from_module_spec(lib, name)
|
[
"def",
"load_extension",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"__extensions",
":",
"raise",
"errors",
".",
"ExtensionAlreadyLoaded",
"(",
"name",
")",
"try",
":",
"lib",
"=",
"importlib",
".",
"import_module",
"(",
"name",
")",
"except",
"ImportError",
"as",
"e",
":",
"raise",
"errors",
".",
"ExtensionNotFound",
"(",
"name",
",",
"e",
")",
"from",
"e",
"else",
":",
"self",
".",
"_load_from_module_spec",
"(",
"lib",
",",
"name",
")"
] |
Loads an extension.
An extension is a python module that contains commands, cogs, or
listeners.
An extension must have a global function, ``setup`` defined as
the entry point on what to do when the extension is loaded. This entry
point must have a single argument, the ``bot``.
Parameters
------------
name: :class:`str`
The extension name to load. It must be dot separated like
regular Python imports if accessing a sub-module. e.g.
``foo.test`` if you want to import ``foo/test.py``.
Raises
--------
ExtensionNotFound
The extension could not be imported.
ExtensionAlreadyLoaded
The extension is already loaded.
NoEntryPointError
The extension does not have a setup function.
ExtensionFailed
The extension setup function had an execution error.
|
[
"Loads",
"an",
"extension",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L584-L621
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.unload_extension
|
def unload_extension(self, name):
"""Unloads an extension.
When the extension is unloaded, all commands, listeners, and cogs are
removed from the bot and the module is un-imported.
The extension can provide an optional global function, ``teardown``,
to do miscellaneous clean-up if necessary. This function takes a single
parameter, the ``bot``, similar to ``setup`` from
:meth:`~.Bot.load_extension`.
Parameters
------------
name: :class:`str`
The extension name to unload. It must be dot separated like
regular Python imports if accessing a sub-module. e.g.
``foo.test`` if you want to import ``foo/test.py``.
Raises
-------
ExtensionNotLoaded
The extension was not loaded.
"""
lib = self.__extensions.get(name)
if lib is None:
raise errors.ExtensionNotLoaded(name)
self._remove_module_references(lib.__name__)
self._call_module_finalizers(lib, name)
|
python
|
def unload_extension(self, name):
"""Unloads an extension.
When the extension is unloaded, all commands, listeners, and cogs are
removed from the bot and the module is un-imported.
The extension can provide an optional global function, ``teardown``,
to do miscellaneous clean-up if necessary. This function takes a single
parameter, the ``bot``, similar to ``setup`` from
:meth:`~.Bot.load_extension`.
Parameters
------------
name: :class:`str`
The extension name to unload. It must be dot separated like
regular Python imports if accessing a sub-module. e.g.
``foo.test`` if you want to import ``foo/test.py``.
Raises
-------
ExtensionNotLoaded
The extension was not loaded.
"""
lib = self.__extensions.get(name)
if lib is None:
raise errors.ExtensionNotLoaded(name)
self._remove_module_references(lib.__name__)
self._call_module_finalizers(lib, name)
|
[
"def",
"unload_extension",
"(",
"self",
",",
"name",
")",
":",
"lib",
"=",
"self",
".",
"__extensions",
".",
"get",
"(",
"name",
")",
"if",
"lib",
"is",
"None",
":",
"raise",
"errors",
".",
"ExtensionNotLoaded",
"(",
"name",
")",
"self",
".",
"_remove_module_references",
"(",
"lib",
".",
"__name__",
")",
"self",
".",
"_call_module_finalizers",
"(",
"lib",
",",
"name",
")"
] |
Unloads an extension.
When the extension is unloaded, all commands, listeners, and cogs are
removed from the bot and the module is un-imported.
The extension can provide an optional global function, ``teardown``,
to do miscellaneous clean-up if necessary. This function takes a single
parameter, the ``bot``, similar to ``setup`` from
:meth:`~.Bot.load_extension`.
Parameters
------------
name: :class:`str`
The extension name to unload. It must be dot separated like
regular Python imports if accessing a sub-module. e.g.
``foo.test`` if you want to import ``foo/test.py``.
Raises
-------
ExtensionNotLoaded
The extension was not loaded.
|
[
"Unloads",
"an",
"extension",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L623-L652
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.reload_extension
|
def reload_extension(self, name):
"""Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is
equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension`
except done in an atomic way. That is, if an operation fails mid-reload then
the bot will roll-back to the prior working state.
Parameters
------------
name: :class:`str`
The extension name to reload. It must be dot separated like
regular Python imports if accessing a sub-module. e.g.
``foo.test`` if you want to import ``foo/test.py``.
Raises
-------
ExtensionNotLoaded
The extension was not loaded.
ExtensionNotFound
The extension could not be imported.
NoEntryPointError
The extension does not have a setup function.
ExtensionFailed
The extension setup function had an execution error.
"""
lib = self.__extensions.get(name)
if lib is None:
raise errors.ExtensionNotLoaded(name)
# get the previous module states from sys modules
modules = {
name: module
for name, module in sys.modules.items()
if _is_submodule(lib.__name__, name)
}
try:
# Unload and then load the module...
self._remove_module_references(lib.__name__)
self._call_module_finalizers(lib, name)
self.load_extension(name)
except Exception as e:
# if the load failed, the remnants should have been
# cleaned from the load_extension function call
# so let's load it from our old compiled library.
self._load_from_module_spec(lib, name)
# revert sys.modules back to normal and raise back to caller
sys.modules.update(modules)
raise
|
python
|
def reload_extension(self, name):
"""Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is
equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension`
except done in an atomic way. That is, if an operation fails mid-reload then
the bot will roll-back to the prior working state.
Parameters
------------
name: :class:`str`
The extension name to reload. It must be dot separated like
regular Python imports if accessing a sub-module. e.g.
``foo.test`` if you want to import ``foo/test.py``.
Raises
-------
ExtensionNotLoaded
The extension was not loaded.
ExtensionNotFound
The extension could not be imported.
NoEntryPointError
The extension does not have a setup function.
ExtensionFailed
The extension setup function had an execution error.
"""
lib = self.__extensions.get(name)
if lib is None:
raise errors.ExtensionNotLoaded(name)
# get the previous module states from sys modules
modules = {
name: module
for name, module in sys.modules.items()
if _is_submodule(lib.__name__, name)
}
try:
# Unload and then load the module...
self._remove_module_references(lib.__name__)
self._call_module_finalizers(lib, name)
self.load_extension(name)
except Exception as e:
# if the load failed, the remnants should have been
# cleaned from the load_extension function call
# so let's load it from our old compiled library.
self._load_from_module_spec(lib, name)
# revert sys.modules back to normal and raise back to caller
sys.modules.update(modules)
raise
|
[
"def",
"reload_extension",
"(",
"self",
",",
"name",
")",
":",
"lib",
"=",
"self",
".",
"__extensions",
".",
"get",
"(",
"name",
")",
"if",
"lib",
"is",
"None",
":",
"raise",
"errors",
".",
"ExtensionNotLoaded",
"(",
"name",
")",
"# get the previous module states from sys modules",
"modules",
"=",
"{",
"name",
":",
"module",
"for",
"name",
",",
"module",
"in",
"sys",
".",
"modules",
".",
"items",
"(",
")",
"if",
"_is_submodule",
"(",
"lib",
".",
"__name__",
",",
"name",
")",
"}",
"try",
":",
"# Unload and then load the module...",
"self",
".",
"_remove_module_references",
"(",
"lib",
".",
"__name__",
")",
"self",
".",
"_call_module_finalizers",
"(",
"lib",
",",
"name",
")",
"self",
".",
"load_extension",
"(",
"name",
")",
"except",
"Exception",
"as",
"e",
":",
"# if the load failed, the remnants should have been",
"# cleaned from the load_extension function call",
"# so let's load it from our old compiled library.",
"self",
".",
"_load_from_module_spec",
"(",
"lib",
",",
"name",
")",
"# revert sys.modules back to normal and raise back to caller",
"sys",
".",
"modules",
".",
"update",
"(",
"modules",
")",
"raise"
] |
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is
equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension`
except done in an atomic way. That is, if an operation fails mid-reload then
the bot will roll-back to the prior working state.
Parameters
------------
name: :class:`str`
The extension name to reload. It must be dot separated like
regular Python imports if accessing a sub-module. e.g.
``foo.test`` if you want to import ``foo/test.py``.
Raises
-------
ExtensionNotLoaded
The extension was not loaded.
ExtensionNotFound
The extension could not be imported.
NoEntryPointError
The extension does not have a setup function.
ExtensionFailed
The extension setup function had an execution error.
|
[
"Atomically",
"reloads",
"an",
"extension",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L654-L705
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.get_prefix
|
async def get_prefix(self, message):
"""|coro|
Retrieves the prefix the bot is listening to
with the message as a context.
Parameters
-----------
message: :class:`discord.Message`
The message context to get the prefix of.
Returns
--------
Union[List[:class:`str`], :class:`str`]
A list of prefixes or a single prefix that the bot is
listening for.
"""
prefix = ret = self.command_prefix
if callable(prefix):
ret = await discord.utils.maybe_coroutine(prefix, self, message)
if not isinstance(ret, str):
try:
ret = list(ret)
except TypeError:
# It's possible that a generator raised this exception. Don't
# replace it with our own error if that's the case.
if isinstance(ret, collections.Iterable):
raise
raise TypeError("command_prefix must be plain string, iterable of strings, or callable "
"returning either of these, not {}".format(ret.__class__.__name__))
if not ret:
raise ValueError("Iterable command_prefix must contain at least one prefix")
return ret
|
python
|
async def get_prefix(self, message):
"""|coro|
Retrieves the prefix the bot is listening to
with the message as a context.
Parameters
-----------
message: :class:`discord.Message`
The message context to get the prefix of.
Returns
--------
Union[List[:class:`str`], :class:`str`]
A list of prefixes or a single prefix that the bot is
listening for.
"""
prefix = ret = self.command_prefix
if callable(prefix):
ret = await discord.utils.maybe_coroutine(prefix, self, message)
if not isinstance(ret, str):
try:
ret = list(ret)
except TypeError:
# It's possible that a generator raised this exception. Don't
# replace it with our own error if that's the case.
if isinstance(ret, collections.Iterable):
raise
raise TypeError("command_prefix must be plain string, iterable of strings, or callable "
"returning either of these, not {}".format(ret.__class__.__name__))
if not ret:
raise ValueError("Iterable command_prefix must contain at least one prefix")
return ret
|
[
"async",
"def",
"get_prefix",
"(",
"self",
",",
"message",
")",
":",
"prefix",
"=",
"ret",
"=",
"self",
".",
"command_prefix",
"if",
"callable",
"(",
"prefix",
")",
":",
"ret",
"=",
"await",
"discord",
".",
"utils",
".",
"maybe_coroutine",
"(",
"prefix",
",",
"self",
",",
"message",
")",
"if",
"not",
"isinstance",
"(",
"ret",
",",
"str",
")",
":",
"try",
":",
"ret",
"=",
"list",
"(",
"ret",
")",
"except",
"TypeError",
":",
"# It's possible that a generator raised this exception. Don't",
"# replace it with our own error if that's the case.",
"if",
"isinstance",
"(",
"ret",
",",
"collections",
".",
"Iterable",
")",
":",
"raise",
"raise",
"TypeError",
"(",
"\"command_prefix must be plain string, iterable of strings, or callable \"",
"\"returning either of these, not {}\"",
".",
"format",
"(",
"ret",
".",
"__class__",
".",
"__name__",
")",
")",
"if",
"not",
"ret",
":",
"raise",
"ValueError",
"(",
"\"Iterable command_prefix must contain at least one prefix\"",
")",
"return",
"ret"
] |
|coro|
Retrieves the prefix the bot is listening to
with the message as a context.
Parameters
-----------
message: :class:`discord.Message`
The message context to get the prefix of.
Returns
--------
Union[List[:class:`str`], :class:`str`]
A list of prefixes or a single prefix that the bot is
listening for.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L735-L771
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.get_context
|
async def get_context(self, message, *, cls=Context):
r"""|coro|
Returns the invocation context from the message.
This is a more low-level counter-part for :meth:`.process_commands`
to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation
context, :attr:`.Context.valid` must be checked to make sure it is.
If the context is not valid then it is not a valid candidate to be
invoked under :meth:`~.Bot.invoke`.
Parameters
-----------
message: :class:`discord.Message`
The message to get the invocation context from.
cls
The factory class that will be used to create the context.
By default, this is :class:`.Context`. Should a custom
class be provided, it must be similar enough to :class:`.Context`\'s
interface.
Returns
--------
:class:`.Context`
The invocation context. The type of this can change via the
``cls`` parameter.
"""
view = StringView(message.content)
ctx = cls(prefix=None, view=view, bot=self, message=message)
if self._skip_check(message.author.id, self.user.id):
return ctx
prefix = await self.get_prefix(message)
invoked_prefix = prefix
if isinstance(prefix, str):
if not view.skip_string(prefix):
return ctx
else:
try:
# if the context class' __init__ consumes something from the view this
# will be wrong. That seems unreasonable though.
if message.content.startswith(tuple(prefix)):
invoked_prefix = discord.utils.find(view.skip_string, prefix)
else:
return ctx
except TypeError:
if not isinstance(prefix, list):
raise TypeError("get_prefix must return either a string or a list of string, "
"not {}".format(prefix.__class__.__name__))
# It's possible a bad command_prefix got us here.
for value in prefix:
if not isinstance(value, str):
raise TypeError("Iterable command_prefix or list returned from get_prefix must "
"contain only strings, not {}".format(value.__class__.__name__))
# Getting here shouldn't happen
raise
invoker = view.get_word()
ctx.invoked_with = invoker
ctx.prefix = invoked_prefix
ctx.command = self.all_commands.get(invoker)
return ctx
|
python
|
async def get_context(self, message, *, cls=Context):
r"""|coro|
Returns the invocation context from the message.
This is a more low-level counter-part for :meth:`.process_commands`
to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation
context, :attr:`.Context.valid` must be checked to make sure it is.
If the context is not valid then it is not a valid candidate to be
invoked under :meth:`~.Bot.invoke`.
Parameters
-----------
message: :class:`discord.Message`
The message to get the invocation context from.
cls
The factory class that will be used to create the context.
By default, this is :class:`.Context`. Should a custom
class be provided, it must be similar enough to :class:`.Context`\'s
interface.
Returns
--------
:class:`.Context`
The invocation context. The type of this can change via the
``cls`` parameter.
"""
view = StringView(message.content)
ctx = cls(prefix=None, view=view, bot=self, message=message)
if self._skip_check(message.author.id, self.user.id):
return ctx
prefix = await self.get_prefix(message)
invoked_prefix = prefix
if isinstance(prefix, str):
if not view.skip_string(prefix):
return ctx
else:
try:
# if the context class' __init__ consumes something from the view this
# will be wrong. That seems unreasonable though.
if message.content.startswith(tuple(prefix)):
invoked_prefix = discord.utils.find(view.skip_string, prefix)
else:
return ctx
except TypeError:
if not isinstance(prefix, list):
raise TypeError("get_prefix must return either a string or a list of string, "
"not {}".format(prefix.__class__.__name__))
# It's possible a bad command_prefix got us here.
for value in prefix:
if not isinstance(value, str):
raise TypeError("Iterable command_prefix or list returned from get_prefix must "
"contain only strings, not {}".format(value.__class__.__name__))
# Getting here shouldn't happen
raise
invoker = view.get_word()
ctx.invoked_with = invoker
ctx.prefix = invoked_prefix
ctx.command = self.all_commands.get(invoker)
return ctx
|
[
"async",
"def",
"get_context",
"(",
"self",
",",
"message",
",",
"*",
",",
"cls",
"=",
"Context",
")",
":",
"view",
"=",
"StringView",
"(",
"message",
".",
"content",
")",
"ctx",
"=",
"cls",
"(",
"prefix",
"=",
"None",
",",
"view",
"=",
"view",
",",
"bot",
"=",
"self",
",",
"message",
"=",
"message",
")",
"if",
"self",
".",
"_skip_check",
"(",
"message",
".",
"author",
".",
"id",
",",
"self",
".",
"user",
".",
"id",
")",
":",
"return",
"ctx",
"prefix",
"=",
"await",
"self",
".",
"get_prefix",
"(",
"message",
")",
"invoked_prefix",
"=",
"prefix",
"if",
"isinstance",
"(",
"prefix",
",",
"str",
")",
":",
"if",
"not",
"view",
".",
"skip_string",
"(",
"prefix",
")",
":",
"return",
"ctx",
"else",
":",
"try",
":",
"# if the context class' __init__ consumes something from the view this",
"# will be wrong. That seems unreasonable though.",
"if",
"message",
".",
"content",
".",
"startswith",
"(",
"tuple",
"(",
"prefix",
")",
")",
":",
"invoked_prefix",
"=",
"discord",
".",
"utils",
".",
"find",
"(",
"view",
".",
"skip_string",
",",
"prefix",
")",
"else",
":",
"return",
"ctx",
"except",
"TypeError",
":",
"if",
"not",
"isinstance",
"(",
"prefix",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"get_prefix must return either a string or a list of string, \"",
"\"not {}\"",
".",
"format",
"(",
"prefix",
".",
"__class__",
".",
"__name__",
")",
")",
"# It's possible a bad command_prefix got us here.",
"for",
"value",
"in",
"prefix",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"Iterable command_prefix or list returned from get_prefix must \"",
"\"contain only strings, not {}\"",
".",
"format",
"(",
"value",
".",
"__class__",
".",
"__name__",
")",
")",
"# Getting here shouldn't happen",
"raise",
"invoker",
"=",
"view",
".",
"get_word",
"(",
")",
"ctx",
".",
"invoked_with",
"=",
"invoker",
"ctx",
".",
"prefix",
"=",
"invoked_prefix",
"ctx",
".",
"command",
"=",
"self",
".",
"all_commands",
".",
"get",
"(",
"invoker",
")",
"return",
"ctx"
] |
r"""|coro|
Returns the invocation context from the message.
This is a more low-level counter-part for :meth:`.process_commands`
to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation
context, :attr:`.Context.valid` must be checked to make sure it is.
If the context is not valid then it is not a valid candidate to be
invoked under :meth:`~.Bot.invoke`.
Parameters
-----------
message: :class:`discord.Message`
The message to get the invocation context from.
cls
The factory class that will be used to create the context.
By default, this is :class:`.Context`. Should a custom
class be provided, it must be similar enough to :class:`.Context`\'s
interface.
Returns
--------
:class:`.Context`
The invocation context. The type of this can change via the
``cls`` parameter.
|
[
"r",
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L773-L842
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.invoke
|
async def invoke(self, ctx):
"""|coro|
Invokes the command given under the invocation context and
handles all the internal event dispatch mechanisms.
Parameters
-----------
ctx: :class:`.Context`
The invocation context to invoke.
"""
if ctx.command is not None:
self.dispatch('command', ctx)
try:
if await self.can_run(ctx, call_once=True):
await ctx.command.invoke(ctx)
except errors.CommandError as exc:
await ctx.command.dispatch_error(ctx, exc)
else:
self.dispatch('command_completion', ctx)
elif ctx.invoked_with:
exc = errors.CommandNotFound('Command "{}" is not found'.format(ctx.invoked_with))
self.dispatch('command_error', ctx, exc)
|
python
|
async def invoke(self, ctx):
"""|coro|
Invokes the command given under the invocation context and
handles all the internal event dispatch mechanisms.
Parameters
-----------
ctx: :class:`.Context`
The invocation context to invoke.
"""
if ctx.command is not None:
self.dispatch('command', ctx)
try:
if await self.can_run(ctx, call_once=True):
await ctx.command.invoke(ctx)
except errors.CommandError as exc:
await ctx.command.dispatch_error(ctx, exc)
else:
self.dispatch('command_completion', ctx)
elif ctx.invoked_with:
exc = errors.CommandNotFound('Command "{}" is not found'.format(ctx.invoked_with))
self.dispatch('command_error', ctx, exc)
|
[
"async",
"def",
"invoke",
"(",
"self",
",",
"ctx",
")",
":",
"if",
"ctx",
".",
"command",
"is",
"not",
"None",
":",
"self",
".",
"dispatch",
"(",
"'command'",
",",
"ctx",
")",
"try",
":",
"if",
"await",
"self",
".",
"can_run",
"(",
"ctx",
",",
"call_once",
"=",
"True",
")",
":",
"await",
"ctx",
".",
"command",
".",
"invoke",
"(",
"ctx",
")",
"except",
"errors",
".",
"CommandError",
"as",
"exc",
":",
"await",
"ctx",
".",
"command",
".",
"dispatch_error",
"(",
"ctx",
",",
"exc",
")",
"else",
":",
"self",
".",
"dispatch",
"(",
"'command_completion'",
",",
"ctx",
")",
"elif",
"ctx",
".",
"invoked_with",
":",
"exc",
"=",
"errors",
".",
"CommandNotFound",
"(",
"'Command \"{}\" is not found'",
".",
"format",
"(",
"ctx",
".",
"invoked_with",
")",
")",
"self",
".",
"dispatch",
"(",
"'command_error'",
",",
"ctx",
",",
"exc",
")"
] |
|coro|
Invokes the command given under the invocation context and
handles all the internal event dispatch mechanisms.
Parameters
-----------
ctx: :class:`.Context`
The invocation context to invoke.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L844-L866
|
train
|
Rapptz/discord.py
|
discord/ext/commands/bot.py
|
BotBase.process_commands
|
async def process_commands(self, message):
"""|coro|
This function processes the commands that have been registered
to the bot and other groups. Without this coroutine, none of the
commands will be triggered.
By default, this coroutine is called inside the :func:`.on_message`
event. If you choose to override the :func:`.on_message` event, then
you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a
call to :meth:`~.Bot.get_context` followed by a call to :meth:`~.Bot.invoke`.
This also checks if the message's author is a bot and doesn't
call :meth:`~.Bot.get_context` or :meth:`~.Bot.invoke` if so.
Parameters
-----------
message: :class:`discord.Message`
The message to process commands for.
"""
if message.author.bot:
return
ctx = await self.get_context(message)
await self.invoke(ctx)
|
python
|
async def process_commands(self, message):
"""|coro|
This function processes the commands that have been registered
to the bot and other groups. Without this coroutine, none of the
commands will be triggered.
By default, this coroutine is called inside the :func:`.on_message`
event. If you choose to override the :func:`.on_message` event, then
you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a
call to :meth:`~.Bot.get_context` followed by a call to :meth:`~.Bot.invoke`.
This also checks if the message's author is a bot and doesn't
call :meth:`~.Bot.get_context` or :meth:`~.Bot.invoke` if so.
Parameters
-----------
message: :class:`discord.Message`
The message to process commands for.
"""
if message.author.bot:
return
ctx = await self.get_context(message)
await self.invoke(ctx)
|
[
"async",
"def",
"process_commands",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
".",
"author",
".",
"bot",
":",
"return",
"ctx",
"=",
"await",
"self",
".",
"get_context",
"(",
"message",
")",
"await",
"self",
".",
"invoke",
"(",
"ctx",
")"
] |
|coro|
This function processes the commands that have been registered
to the bot and other groups. Without this coroutine, none of the
commands will be triggered.
By default, this coroutine is called inside the :func:`.on_message`
event. If you choose to override the :func:`.on_message` event, then
you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a
call to :meth:`~.Bot.get_context` followed by a call to :meth:`~.Bot.invoke`.
This also checks if the message's author is a bot and doesn't
call :meth:`~.Bot.get_context` or :meth:`~.Bot.invoke` if so.
Parameters
-----------
message: :class:`discord.Message`
The message to process commands for.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L868-L894
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.large
|
def large(self):
""":class:`bool`: Indicates if the guild is a 'large' guild.
A large guild is defined as having more than ``large_threshold`` count
members, which for this library is set to the maximum of 250.
"""
if self._large is None:
try:
return self._member_count >= 250
except AttributeError:
return len(self._members) >= 250
return self._large
|
python
|
def large(self):
""":class:`bool`: Indicates if the guild is a 'large' guild.
A large guild is defined as having more than ``large_threshold`` count
members, which for this library is set to the maximum of 250.
"""
if self._large is None:
try:
return self._member_count >= 250
except AttributeError:
return len(self._members) >= 250
return self._large
|
[
"def",
"large",
"(",
"self",
")",
":",
"if",
"self",
".",
"_large",
"is",
"None",
":",
"try",
":",
"return",
"self",
".",
"_member_count",
">=",
"250",
"except",
"AttributeError",
":",
"return",
"len",
"(",
"self",
".",
"_members",
")",
">=",
"250",
"return",
"self",
".",
"_large"
] |
:class:`bool`: Indicates if the guild is a 'large' guild.
A large guild is defined as having more than ``large_threshold`` count
members, which for this library is set to the maximum of 250.
|
[
":",
"class",
":",
"bool",
":",
"Indicates",
"if",
"the",
"guild",
"is",
"a",
"large",
"guild",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L287-L298
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.voice_channels
|
def voice_channels(self):
"""List[:class:`VoiceChannel`]: A list of voice channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, VoiceChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
|
python
|
def voice_channels(self):
"""List[:class:`VoiceChannel`]: A list of voice channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, VoiceChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
|
[
"def",
"voice_channels",
"(",
"self",
")",
":",
"r",
"=",
"[",
"ch",
"for",
"ch",
"in",
"self",
".",
"_channels",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"ch",
",",
"VoiceChannel",
")",
"]",
"r",
".",
"sort",
"(",
"key",
"=",
"lambda",
"c",
":",
"(",
"c",
".",
"position",
",",
"c",
".",
"id",
")",
")",
"return",
"r"
] |
List[:class:`VoiceChannel`]: A list of voice channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
|
[
"List",
"[",
":",
"class",
":",
"VoiceChannel",
"]",
":",
"A",
"list",
"of",
"voice",
"channels",
"that",
"belongs",
"to",
"this",
"guild",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L301-L308
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.me
|
def me(self):
"""Similar to :attr:`Client.user` except an instance of :class:`Member`.
This is essentially used to get the member version of yourself.
"""
self_id = self._state.user.id
return self.get_member(self_id)
|
python
|
def me(self):
"""Similar to :attr:`Client.user` except an instance of :class:`Member`.
This is essentially used to get the member version of yourself.
"""
self_id = self._state.user.id
return self.get_member(self_id)
|
[
"def",
"me",
"(",
"self",
")",
":",
"self_id",
"=",
"self",
".",
"_state",
".",
"user",
".",
"id",
"return",
"self",
".",
"get_member",
"(",
"self_id",
")"
] |
Similar to :attr:`Client.user` except an instance of :class:`Member`.
This is essentially used to get the member version of yourself.
|
[
"Similar",
"to",
":",
"attr",
":",
"Client",
".",
"user",
"except",
"an",
"instance",
"of",
":",
"class",
":",
"Member",
".",
"This",
"is",
"essentially",
"used",
"to",
"get",
"the",
"member",
"version",
"of",
"yourself",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L311-L316
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.text_channels
|
def text_channels(self):
"""List[:class:`TextChannel`]: A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, TextChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
|
python
|
def text_channels(self):
"""List[:class:`TextChannel`]: A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, TextChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
|
[
"def",
"text_channels",
"(",
"self",
")",
":",
"r",
"=",
"[",
"ch",
"for",
"ch",
"in",
"self",
".",
"_channels",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"ch",
",",
"TextChannel",
")",
"]",
"r",
".",
"sort",
"(",
"key",
"=",
"lambda",
"c",
":",
"(",
"c",
".",
"position",
",",
"c",
".",
"id",
")",
")",
"return",
"r"
] |
List[:class:`TextChannel`]: A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
|
[
"List",
"[",
":",
"class",
":",
"TextChannel",
"]",
":",
"A",
"list",
"of",
"text",
"channels",
"that",
"belongs",
"to",
"this",
"guild",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L324-L331
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.categories
|
def categories(self):
"""List[:class:`CategoryChannel`]: A list of categories that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, CategoryChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
|
python
|
def categories(self):
"""List[:class:`CategoryChannel`]: A list of categories that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, CategoryChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
|
[
"def",
"categories",
"(",
"self",
")",
":",
"r",
"=",
"[",
"ch",
"for",
"ch",
"in",
"self",
".",
"_channels",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"ch",
",",
"CategoryChannel",
")",
"]",
"r",
".",
"sort",
"(",
"key",
"=",
"lambda",
"c",
":",
"(",
"c",
".",
"position",
",",
"c",
".",
"id",
")",
")",
"return",
"r"
] |
List[:class:`CategoryChannel`]: A list of categories that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
|
[
"List",
"[",
":",
"class",
":",
"CategoryChannel",
"]",
":",
"A",
"list",
"of",
"categories",
"that",
"belongs",
"to",
"this",
"guild",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L334-L341
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.by_category
|
def by_category(self):
"""Returns every :class:`CategoryChannel` and their associated channels.
These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
``None``.
Returns
--------
List[Tuple[Optional[:class:`CategoryChannel`], List[:class:`abc.GuildChannel`]]]:
The categories and their associated channels.
"""
grouped = defaultdict(list)
for channel in self._channels.values():
if isinstance(channel, CategoryChannel):
continue
grouped[channel.category_id].append(channel)
def key(t):
k, v = t
return ((k.position, k.id) if k else (-1, -1), v)
_get = self._channels.get
as_list = [(_get(k), v) for k, v in grouped.items()]
as_list.sort(key=key)
for _, channels in as_list:
channels.sort(key=lambda c: (c._sorting_bucket, c.position, c.id))
return as_list
|
python
|
def by_category(self):
"""Returns every :class:`CategoryChannel` and their associated channels.
These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
``None``.
Returns
--------
List[Tuple[Optional[:class:`CategoryChannel`], List[:class:`abc.GuildChannel`]]]:
The categories and their associated channels.
"""
grouped = defaultdict(list)
for channel in self._channels.values():
if isinstance(channel, CategoryChannel):
continue
grouped[channel.category_id].append(channel)
def key(t):
k, v = t
return ((k.position, k.id) if k else (-1, -1), v)
_get = self._channels.get
as_list = [(_get(k), v) for k, v in grouped.items()]
as_list.sort(key=key)
for _, channels in as_list:
channels.sort(key=lambda c: (c._sorting_bucket, c.position, c.id))
return as_list
|
[
"def",
"by_category",
"(",
"self",
")",
":",
"grouped",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"channel",
"in",
"self",
".",
"_channels",
".",
"values",
"(",
")",
":",
"if",
"isinstance",
"(",
"channel",
",",
"CategoryChannel",
")",
":",
"continue",
"grouped",
"[",
"channel",
".",
"category_id",
"]",
".",
"append",
"(",
"channel",
")",
"def",
"key",
"(",
"t",
")",
":",
"k",
",",
"v",
"=",
"t",
"return",
"(",
"(",
"k",
".",
"position",
",",
"k",
".",
"id",
")",
"if",
"k",
"else",
"(",
"-",
"1",
",",
"-",
"1",
")",
",",
"v",
")",
"_get",
"=",
"self",
".",
"_channels",
".",
"get",
"as_list",
"=",
"[",
"(",
"_get",
"(",
"k",
")",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"grouped",
".",
"items",
"(",
")",
"]",
"as_list",
".",
"sort",
"(",
"key",
"=",
"key",
")",
"for",
"_",
",",
"channels",
"in",
"as_list",
":",
"channels",
".",
"sort",
"(",
"key",
"=",
"lambda",
"c",
":",
"(",
"c",
".",
"_sorting_bucket",
",",
"c",
".",
"position",
",",
"c",
".",
"id",
")",
")",
"return",
"as_list"
] |
Returns every :class:`CategoryChannel` and their associated channels.
These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
``None``.
Returns
--------
List[Tuple[Optional[:class:`CategoryChannel`], List[:class:`abc.GuildChannel`]]]:
The categories and their associated channels.
|
[
"Returns",
"every",
":",
"class",
":",
"CategoryChannel",
"and",
"their",
"associated",
"channels",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L343-L372
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.system_channel
|
def system_channel(self):
"""Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages.
Currently this is only for new member joins. If no channel is set, then this returns ``None``.
"""
channel_id = self._system_channel_id
return channel_id and self._channels.get(channel_id)
|
python
|
def system_channel(self):
"""Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages.
Currently this is only for new member joins. If no channel is set, then this returns ``None``.
"""
channel_id = self._system_channel_id
return channel_id and self._channels.get(channel_id)
|
[
"def",
"system_channel",
"(",
"self",
")",
":",
"channel_id",
"=",
"self",
".",
"_system_channel_id",
"return",
"channel_id",
"and",
"self",
".",
"_channels",
".",
"get",
"(",
"channel_id",
")"
] |
Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages.
Currently this is only for new member joins. If no channel is set, then this returns ``None``.
|
[
"Optional",
"[",
":",
"class",
":",
"TextChannel",
"]",
":",
"Returns",
"the",
"guild",
"s",
"channel",
"used",
"for",
"system",
"messages",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L379-L385
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.default_role
|
def default_role(self):
"""Gets the @everyone role that all members have by default."""
return utils.find(lambda r: r.is_default(), self._roles.values())
|
python
|
def default_role(self):
"""Gets the @everyone role that all members have by default."""
return utils.find(lambda r: r.is_default(), self._roles.values())
|
[
"def",
"default_role",
"(",
"self",
")",
":",
"return",
"utils",
".",
"find",
"(",
"lambda",
"r",
":",
"r",
".",
"is_default",
"(",
")",
",",
"self",
".",
"_roles",
".",
"values",
"(",
")",
")"
] |
Gets the @everyone role that all members have by default.
|
[
"Gets",
"the"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L410-L412
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.chunked
|
def chunked(self):
"""Returns a boolean indicating if the guild is "chunked".
A chunked guild means that :attr:`member_count` is equal to the
number of members stored in the internal :attr:`members` cache.
If this value returns ``False``, then you should request for
offline members.
"""
count = getattr(self, '_member_count', None)
if count is None:
return False
return count == len(self._members)
|
python
|
def chunked(self):
"""Returns a boolean indicating if the guild is "chunked".
A chunked guild means that :attr:`member_count` is equal to the
number of members stored in the internal :attr:`members` cache.
If this value returns ``False``, then you should request for
offline members.
"""
count = getattr(self, '_member_count', None)
if count is None:
return False
return count == len(self._members)
|
[
"def",
"chunked",
"(",
"self",
")",
":",
"count",
"=",
"getattr",
"(",
"self",
",",
"'_member_count'",
",",
"None",
")",
"if",
"count",
"is",
"None",
":",
"return",
"False",
"return",
"count",
"==",
"len",
"(",
"self",
".",
"_members",
")"
] |
Returns a boolean indicating if the guild is "chunked".
A chunked guild means that :attr:`member_count` is equal to the
number of members stored in the internal :attr:`members` cache.
If this value returns ``False``, then you should request for
offline members.
|
[
"Returns",
"a",
"boolean",
"indicating",
"if",
"the",
"guild",
"is",
"chunked",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L515-L527
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.shard_id
|
def shard_id(self):
"""Returns the shard ID for this guild if applicable."""
count = self._state.shard_count
if count is None:
return None
return (self.id >> 22) % count
|
python
|
def shard_id(self):
"""Returns the shard ID for this guild if applicable."""
count = self._state.shard_count
if count is None:
return None
return (self.id >> 22) % count
|
[
"def",
"shard_id",
"(",
"self",
")",
":",
"count",
"=",
"self",
".",
"_state",
".",
"shard_count",
"if",
"count",
"is",
"None",
":",
"return",
"None",
"return",
"(",
"self",
".",
"id",
">>",
"22",
")",
"%",
"count"
] |
Returns the shard ID for this guild if applicable.
|
[
"Returns",
"the",
"shard",
"ID",
"for",
"this",
"guild",
"if",
"applicable",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L530-L535
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.get_member_named
|
def get_member_named(self, name):
"""Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. "Jake#0001"
or "Jake" will both do the lookup. However the former will give a more
precise result. Note that the discriminator must have all 4 digits
for this to work.
If a nickname is passed, then it is looked up via the nickname. Note
however, that a nickname + discriminator combo will not lookup the nickname
but rather the username + discriminator combo due to nickname + discriminator
not being unique.
If no member is found, ``None`` is returned.
Parameters
-----------
name: :class:`str`
The name of the member to lookup with an optional discriminator.
Returns
--------
:class:`Member`
The member in this guild with the associated name. If not found
then ``None`` is returned.
"""
result = None
members = self.members
if len(name) > 5 and name[-5] == '#':
# The 5 length is checking to see if #0000 is in the string,
# as a#0000 has a length of 6, the minimum for a potential
# discriminator lookup.
potential_discriminator = name[-4:]
# do the actual lookup and return if found
# if it isn't found then we'll do a full name lookup below.
result = utils.get(members, name=name[:-5], discriminator=potential_discriminator)
if result is not None:
return result
def pred(m):
return m.nick == name or m.name == name
return utils.find(pred, members)
|
python
|
def get_member_named(self, name):
"""Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. "Jake#0001"
or "Jake" will both do the lookup. However the former will give a more
precise result. Note that the discriminator must have all 4 digits
for this to work.
If a nickname is passed, then it is looked up via the nickname. Note
however, that a nickname + discriminator combo will not lookup the nickname
but rather the username + discriminator combo due to nickname + discriminator
not being unique.
If no member is found, ``None`` is returned.
Parameters
-----------
name: :class:`str`
The name of the member to lookup with an optional discriminator.
Returns
--------
:class:`Member`
The member in this guild with the associated name. If not found
then ``None`` is returned.
"""
result = None
members = self.members
if len(name) > 5 and name[-5] == '#':
# The 5 length is checking to see if #0000 is in the string,
# as a#0000 has a length of 6, the minimum for a potential
# discriminator lookup.
potential_discriminator = name[-4:]
# do the actual lookup and return if found
# if it isn't found then we'll do a full name lookup below.
result = utils.get(members, name=name[:-5], discriminator=potential_discriminator)
if result is not None:
return result
def pred(m):
return m.nick == name or m.name == name
return utils.find(pred, members)
|
[
"def",
"get_member_named",
"(",
"self",
",",
"name",
")",
":",
"result",
"=",
"None",
"members",
"=",
"self",
".",
"members",
"if",
"len",
"(",
"name",
")",
">",
"5",
"and",
"name",
"[",
"-",
"5",
"]",
"==",
"'#'",
":",
"# The 5 length is checking to see if #0000 is in the string,",
"# as a#0000 has a length of 6, the minimum for a potential",
"# discriminator lookup.",
"potential_discriminator",
"=",
"name",
"[",
"-",
"4",
":",
"]",
"# do the actual lookup and return if found",
"# if it isn't found then we'll do a full name lookup below.",
"result",
"=",
"utils",
".",
"get",
"(",
"members",
",",
"name",
"=",
"name",
"[",
":",
"-",
"5",
"]",
",",
"discriminator",
"=",
"potential_discriminator",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"def",
"pred",
"(",
"m",
")",
":",
"return",
"m",
".",
"nick",
"==",
"name",
"or",
"m",
".",
"name",
"==",
"name",
"return",
"utils",
".",
"find",
"(",
"pred",
",",
"members",
")"
] |
Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. "Jake#0001"
or "Jake" will both do the lookup. However the former will give a more
precise result. Note that the discriminator must have all 4 digits
for this to work.
If a nickname is passed, then it is looked up via the nickname. Note
however, that a nickname + discriminator combo will not lookup the nickname
but rather the username + discriminator combo due to nickname + discriminator
not being unique.
If no member is found, ``None`` is returned.
Parameters
-----------
name: :class:`str`
The name of the member to lookup with an optional discriminator.
Returns
--------
:class:`Member`
The member in this guild with the associated name. If not found
then ``None`` is returned.
|
[
"Returns",
"the",
"first",
"member",
"found",
"that",
"matches",
"the",
"name",
"provided",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L542-L586
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.create_text_channel
|
async def create_text_channel(self, name, *, overwrites=None, category=None, reason=None, **options):
"""|coro|
Creates a :class:`TextChannel` for the guild.
Note that you need the :attr:`~Permissions.manage_channels` permission
to create the channel.
The ``overwrites`` parameter can be used to create a 'secret'
channel upon creation. This parameter expects a :class:`dict` of
overwrites with the target (either a :class:`Member` or a :class:`Role`)
as the key and a :class:`PermissionOverwrite` as the value.
.. note::
Creating a channel of a specified position will not update the position of
other channels to follow suit. A follow-up call to :meth:`~TextChannel.edit`
will be required to update the position of the channel in the channel list.
Examples
----------
Creating a basic channel:
.. code-block:: python3
channel = await guild.create_text_channel('cool-channel')
Creating a "secret" channel:
.. code-block:: python3
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
guild.me: discord.PermissionOverwrite(read_messages=True)
}
channel = await guild.create_text_channel('secret', overwrites=overwrites)
Parameters
-----------
name: :class:`str`
The channel's name.
overwrites
A :class:`dict` of target (either a role or a member) to
:class:`PermissionOverwrite` to apply upon creation of a channel.
Useful for creating secret channels.
category: Optional[:class:`CategoryChannel`]
The category to place the newly created channel under.
The permissions will be automatically synced to category if no
overwrites are provided.
position: :class:`int`
The position in the channel list. This is a number that starts
at 0. e.g. the top channel is position 0.
topic: Optional[:class:`str`]
The new channel's topic.
slowmode_delay: :class:`int`
Specifies the slowmode rate limit for user in this channel.
The maximum value possible is `120`.
nsfw: :class:`bool`
To mark the channel as NSFW or not.
reason: Optional[:class:`str`]
The reason for creating this channel. Shows up on the audit log.
Raises
-------
Forbidden
You do not have the proper permissions to create this channel.
HTTPException
Creating the channel failed.
InvalidArgument
The permission overwrite information is not in proper form.
Returns
-------
:class:`TextChannel`
The channel that was just created.
"""
data = await self._create_channel(name, overwrites, ChannelType.text, category, reason=reason, **options)
channel = TextChannel(state=self._state, guild=self, data=data)
# temporarily add to the cache
self._channels[channel.id] = channel
return channel
|
python
|
async def create_text_channel(self, name, *, overwrites=None, category=None, reason=None, **options):
"""|coro|
Creates a :class:`TextChannel` for the guild.
Note that you need the :attr:`~Permissions.manage_channels` permission
to create the channel.
The ``overwrites`` parameter can be used to create a 'secret'
channel upon creation. This parameter expects a :class:`dict` of
overwrites with the target (either a :class:`Member` or a :class:`Role`)
as the key and a :class:`PermissionOverwrite` as the value.
.. note::
Creating a channel of a specified position will not update the position of
other channels to follow suit. A follow-up call to :meth:`~TextChannel.edit`
will be required to update the position of the channel in the channel list.
Examples
----------
Creating a basic channel:
.. code-block:: python3
channel = await guild.create_text_channel('cool-channel')
Creating a "secret" channel:
.. code-block:: python3
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
guild.me: discord.PermissionOverwrite(read_messages=True)
}
channel = await guild.create_text_channel('secret', overwrites=overwrites)
Parameters
-----------
name: :class:`str`
The channel's name.
overwrites
A :class:`dict` of target (either a role or a member) to
:class:`PermissionOverwrite` to apply upon creation of a channel.
Useful for creating secret channels.
category: Optional[:class:`CategoryChannel`]
The category to place the newly created channel under.
The permissions will be automatically synced to category if no
overwrites are provided.
position: :class:`int`
The position in the channel list. This is a number that starts
at 0. e.g. the top channel is position 0.
topic: Optional[:class:`str`]
The new channel's topic.
slowmode_delay: :class:`int`
Specifies the slowmode rate limit for user in this channel.
The maximum value possible is `120`.
nsfw: :class:`bool`
To mark the channel as NSFW or not.
reason: Optional[:class:`str`]
The reason for creating this channel. Shows up on the audit log.
Raises
-------
Forbidden
You do not have the proper permissions to create this channel.
HTTPException
Creating the channel failed.
InvalidArgument
The permission overwrite information is not in proper form.
Returns
-------
:class:`TextChannel`
The channel that was just created.
"""
data = await self._create_channel(name, overwrites, ChannelType.text, category, reason=reason, **options)
channel = TextChannel(state=self._state, guild=self, data=data)
# temporarily add to the cache
self._channels[channel.id] = channel
return channel
|
[
"async",
"def",
"create_text_channel",
"(",
"self",
",",
"name",
",",
"*",
",",
"overwrites",
"=",
"None",
",",
"category",
"=",
"None",
",",
"reason",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"data",
"=",
"await",
"self",
".",
"_create_channel",
"(",
"name",
",",
"overwrites",
",",
"ChannelType",
".",
"text",
",",
"category",
",",
"reason",
"=",
"reason",
",",
"*",
"*",
"options",
")",
"channel",
"=",
"TextChannel",
"(",
"state",
"=",
"self",
".",
"_state",
",",
"guild",
"=",
"self",
",",
"data",
"=",
"data",
")",
"# temporarily add to the cache",
"self",
".",
"_channels",
"[",
"channel",
".",
"id",
"]",
"=",
"channel",
"return",
"channel"
] |
|coro|
Creates a :class:`TextChannel` for the guild.
Note that you need the :attr:`~Permissions.manage_channels` permission
to create the channel.
The ``overwrites`` parameter can be used to create a 'secret'
channel upon creation. This parameter expects a :class:`dict` of
overwrites with the target (either a :class:`Member` or a :class:`Role`)
as the key and a :class:`PermissionOverwrite` as the value.
.. note::
Creating a channel of a specified position will not update the position of
other channels to follow suit. A follow-up call to :meth:`~TextChannel.edit`
will be required to update the position of the channel in the channel list.
Examples
----------
Creating a basic channel:
.. code-block:: python3
channel = await guild.create_text_channel('cool-channel')
Creating a "secret" channel:
.. code-block:: python3
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
guild.me: discord.PermissionOverwrite(read_messages=True)
}
channel = await guild.create_text_channel('secret', overwrites=overwrites)
Parameters
-----------
name: :class:`str`
The channel's name.
overwrites
A :class:`dict` of target (either a role or a member) to
:class:`PermissionOverwrite` to apply upon creation of a channel.
Useful for creating secret channels.
category: Optional[:class:`CategoryChannel`]
The category to place the newly created channel under.
The permissions will be automatically synced to category if no
overwrites are provided.
position: :class:`int`
The position in the channel list. This is a number that starts
at 0. e.g. the top channel is position 0.
topic: Optional[:class:`str`]
The new channel's topic.
slowmode_delay: :class:`int`
Specifies the slowmode rate limit for user in this channel.
The maximum value possible is `120`.
nsfw: :class:`bool`
To mark the channel as NSFW or not.
reason: Optional[:class:`str`]
The reason for creating this channel. Shows up on the audit log.
Raises
-------
Forbidden
You do not have the proper permissions to create this channel.
HTTPException
Creating the channel failed.
InvalidArgument
The permission overwrite information is not in proper form.
Returns
-------
:class:`TextChannel`
The channel that was just created.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L622-L705
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.create_voice_channel
|
async def create_voice_channel(self, name, *, overwrites=None, category=None, reason=None, **options):
"""|coro|
This is similar to :meth:`create_text_channel` except makes a :class:`VoiceChannel` instead, in addition
to having the following new parameters.
Parameters
-----------
bitrate: :class:`int`
The channel's preferred audio bitrate in bits per second.
user_limit: :class:`int`
The channel's limit for number of members that can be in a voice channel.
"""
data = await self._create_channel(name, overwrites, ChannelType.voice, category, reason=reason, **options)
channel = VoiceChannel(state=self._state, guild=self, data=data)
# temporarily add to the cache
self._channels[channel.id] = channel
return channel
|
python
|
async def create_voice_channel(self, name, *, overwrites=None, category=None, reason=None, **options):
"""|coro|
This is similar to :meth:`create_text_channel` except makes a :class:`VoiceChannel` instead, in addition
to having the following new parameters.
Parameters
-----------
bitrate: :class:`int`
The channel's preferred audio bitrate in bits per second.
user_limit: :class:`int`
The channel's limit for number of members that can be in a voice channel.
"""
data = await self._create_channel(name, overwrites, ChannelType.voice, category, reason=reason, **options)
channel = VoiceChannel(state=self._state, guild=self, data=data)
# temporarily add to the cache
self._channels[channel.id] = channel
return channel
|
[
"async",
"def",
"create_voice_channel",
"(",
"self",
",",
"name",
",",
"*",
",",
"overwrites",
"=",
"None",
",",
"category",
"=",
"None",
",",
"reason",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"data",
"=",
"await",
"self",
".",
"_create_channel",
"(",
"name",
",",
"overwrites",
",",
"ChannelType",
".",
"voice",
",",
"category",
",",
"reason",
"=",
"reason",
",",
"*",
"*",
"options",
")",
"channel",
"=",
"VoiceChannel",
"(",
"state",
"=",
"self",
".",
"_state",
",",
"guild",
"=",
"self",
",",
"data",
"=",
"data",
")",
"# temporarily add to the cache",
"self",
".",
"_channels",
"[",
"channel",
".",
"id",
"]",
"=",
"channel",
"return",
"channel"
] |
|coro|
This is similar to :meth:`create_text_channel` except makes a :class:`VoiceChannel` instead, in addition
to having the following new parameters.
Parameters
-----------
bitrate: :class:`int`
The channel's preferred audio bitrate in bits per second.
user_limit: :class:`int`
The channel's limit for number of members that can be in a voice channel.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L707-L725
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.create_category
|
async def create_category(self, name, *, overwrites=None, reason=None):
"""|coro|
Same as :meth:`create_text_channel` except makes a :class:`CategoryChannel` instead.
.. note::
The ``category`` parameter is not supported in this function since categories
cannot have categories.
"""
data = await self._create_channel(name, overwrites, ChannelType.category, reason=reason)
channel = CategoryChannel(state=self._state, guild=self, data=data)
# temporarily add to the cache
self._channels[channel.id] = channel
return channel
|
python
|
async def create_category(self, name, *, overwrites=None, reason=None):
"""|coro|
Same as :meth:`create_text_channel` except makes a :class:`CategoryChannel` instead.
.. note::
The ``category`` parameter is not supported in this function since categories
cannot have categories.
"""
data = await self._create_channel(name, overwrites, ChannelType.category, reason=reason)
channel = CategoryChannel(state=self._state, guild=self, data=data)
# temporarily add to the cache
self._channels[channel.id] = channel
return channel
|
[
"async",
"def",
"create_category",
"(",
"self",
",",
"name",
",",
"*",
",",
"overwrites",
"=",
"None",
",",
"reason",
"=",
"None",
")",
":",
"data",
"=",
"await",
"self",
".",
"_create_channel",
"(",
"name",
",",
"overwrites",
",",
"ChannelType",
".",
"category",
",",
"reason",
"=",
"reason",
")",
"channel",
"=",
"CategoryChannel",
"(",
"state",
"=",
"self",
".",
"_state",
",",
"guild",
"=",
"self",
",",
"data",
"=",
"data",
")",
"# temporarily add to the cache",
"self",
".",
"_channels",
"[",
"channel",
".",
"id",
"]",
"=",
"channel",
"return",
"channel"
] |
|coro|
Same as :meth:`create_text_channel` except makes a :class:`CategoryChannel` instead.
.. note::
The ``category`` parameter is not supported in this function since categories
cannot have categories.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L727-L742
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.edit
|
async def edit(self, *, reason=None, **fields):
"""|coro|
Edits the guild.
You must have the :attr:`~Permissions.manage_guild` permission
to edit the guild.
Parameters
----------
name: :class:`str`
The new name of the guild.
description: :class:`str`
The new description of the guild. This is only available to guilds that
contain `VERIFIED` in :attr:`Guild.features`.
icon: :class:`bytes`
A :term:`py:bytes-like object` representing the icon. Only PNG/JPEG supported.
Could be ``None`` to denote removal of the icon.
banner: :class:`bytes`
A :term:`py:bytes-like object` representing the banner.
Could be ``None`` to denote removal of the banner.
splash: :class:`bytes`
A :term:`py:bytes-like object` representing the invite splash.
Only PNG/JPEG supported. Could be ``None`` to denote removing the
splash. Only available for partnered guilds with ``INVITE_SPLASH``
feature.
region: :class:`VoiceRegion`
The new region for the guild's voice communication.
afk_channel: Optional[:class:`VoiceChannel`]
The new channel that is the AFK channel. Could be ``None`` for no AFK channel.
afk_timeout: :class:`int`
The number of seconds until someone is moved to the AFK channel.
owner: :class:`Member`
The new owner of the guild to transfer ownership to. Note that you must
be owner of the guild to do this.
verification_level: :class:`VerificationLevel`
The new verification level for the guild.
default_notifications: :class:`NotificationLevel`
The new default notification level for the guild.
explicit_content_filter: :class:`ContentFilter`
The new explicit content filter for the guild.
vanity_code: :class:`str`
The new vanity code for the guild.
system_channel: Optional[:class:`TextChannel`]
The new channel that is used for the system channel. Could be ``None`` for no system channel.
reason: Optional[:class:`str`]
The reason for editing this guild. Shows up on the audit log.
Raises
-------
Forbidden
You do not have permissions to edit the guild.
HTTPException
Editing the guild failed.
InvalidArgument
The image format passed in to ``icon`` is invalid. It must be
PNG or JPG. This is also raised if you are not the owner of the
guild and request an ownership transfer.
"""
http = self._state.http
try:
icon_bytes = fields['icon']
except KeyError:
icon = self.icon
else:
if icon_bytes is not None:
icon = utils._bytes_to_base64_data(icon_bytes)
else:
icon = None
try:
banner_bytes = fields['banner']
except KeyError:
banner = self.banner
else:
if banner_bytes is not None:
banner = utils._bytes_to_base64_data(banner_bytes)
else:
banner = None
try:
vanity_code = fields['vanity_code']
except KeyError:
pass
else:
await http.change_vanity_code(self.id, vanity_code, reason=reason)
try:
splash_bytes = fields['splash']
except KeyError:
splash = self.splash
else:
if splash_bytes is not None:
splash = utils._bytes_to_base64_data(splash_bytes)
else:
splash = None
fields['icon'] = icon
fields['banner'] = banner
fields['splash'] = splash
try:
default_message_notifications = int(fields.pop('default_notifications'))
except (TypeError, KeyError):
pass
else:
fields['default_message_notifications'] = default_message_notifications
try:
afk_channel = fields.pop('afk_channel')
except KeyError:
pass
else:
if afk_channel is None:
fields['afk_channel_id'] = afk_channel
else:
fields['afk_channel_id'] = afk_channel.id
try:
system_channel = fields.pop('system_channel')
except KeyError:
pass
else:
if system_channel is None:
fields['system_channel_id'] = system_channel
else:
fields['system_channel_id'] = system_channel.id
if 'owner' in fields:
if self.owner != self.me:
raise InvalidArgument('To transfer ownership you must be the owner of the guild.')
fields['owner_id'] = fields['owner'].id
if 'region' in fields:
fields['region'] = str(fields['region'])
level = fields.get('verification_level', self.verification_level)
if not isinstance(level, VerificationLevel):
raise InvalidArgument('verification_level field must be of type VerificationLevel')
fields['verification_level'] = level.value
explicit_content_filter = fields.get('explicit_content_filter', self.explicit_content_filter)
if not isinstance(explicit_content_filter, ContentFilter):
raise InvalidArgument('explicit_content_filter field must be of type ContentFilter')
fields['explicit_content_filter'] = explicit_content_filter.value
await http.edit_guild(self.id, reason=reason, **fields)
|
python
|
async def edit(self, *, reason=None, **fields):
"""|coro|
Edits the guild.
You must have the :attr:`~Permissions.manage_guild` permission
to edit the guild.
Parameters
----------
name: :class:`str`
The new name of the guild.
description: :class:`str`
The new description of the guild. This is only available to guilds that
contain `VERIFIED` in :attr:`Guild.features`.
icon: :class:`bytes`
A :term:`py:bytes-like object` representing the icon. Only PNG/JPEG supported.
Could be ``None`` to denote removal of the icon.
banner: :class:`bytes`
A :term:`py:bytes-like object` representing the banner.
Could be ``None`` to denote removal of the banner.
splash: :class:`bytes`
A :term:`py:bytes-like object` representing the invite splash.
Only PNG/JPEG supported. Could be ``None`` to denote removing the
splash. Only available for partnered guilds with ``INVITE_SPLASH``
feature.
region: :class:`VoiceRegion`
The new region for the guild's voice communication.
afk_channel: Optional[:class:`VoiceChannel`]
The new channel that is the AFK channel. Could be ``None`` for no AFK channel.
afk_timeout: :class:`int`
The number of seconds until someone is moved to the AFK channel.
owner: :class:`Member`
The new owner of the guild to transfer ownership to. Note that you must
be owner of the guild to do this.
verification_level: :class:`VerificationLevel`
The new verification level for the guild.
default_notifications: :class:`NotificationLevel`
The new default notification level for the guild.
explicit_content_filter: :class:`ContentFilter`
The new explicit content filter for the guild.
vanity_code: :class:`str`
The new vanity code for the guild.
system_channel: Optional[:class:`TextChannel`]
The new channel that is used for the system channel. Could be ``None`` for no system channel.
reason: Optional[:class:`str`]
The reason for editing this guild. Shows up on the audit log.
Raises
-------
Forbidden
You do not have permissions to edit the guild.
HTTPException
Editing the guild failed.
InvalidArgument
The image format passed in to ``icon`` is invalid. It must be
PNG or JPG. This is also raised if you are not the owner of the
guild and request an ownership transfer.
"""
http = self._state.http
try:
icon_bytes = fields['icon']
except KeyError:
icon = self.icon
else:
if icon_bytes is not None:
icon = utils._bytes_to_base64_data(icon_bytes)
else:
icon = None
try:
banner_bytes = fields['banner']
except KeyError:
banner = self.banner
else:
if banner_bytes is not None:
banner = utils._bytes_to_base64_data(banner_bytes)
else:
banner = None
try:
vanity_code = fields['vanity_code']
except KeyError:
pass
else:
await http.change_vanity_code(self.id, vanity_code, reason=reason)
try:
splash_bytes = fields['splash']
except KeyError:
splash = self.splash
else:
if splash_bytes is not None:
splash = utils._bytes_to_base64_data(splash_bytes)
else:
splash = None
fields['icon'] = icon
fields['banner'] = banner
fields['splash'] = splash
try:
default_message_notifications = int(fields.pop('default_notifications'))
except (TypeError, KeyError):
pass
else:
fields['default_message_notifications'] = default_message_notifications
try:
afk_channel = fields.pop('afk_channel')
except KeyError:
pass
else:
if afk_channel is None:
fields['afk_channel_id'] = afk_channel
else:
fields['afk_channel_id'] = afk_channel.id
try:
system_channel = fields.pop('system_channel')
except KeyError:
pass
else:
if system_channel is None:
fields['system_channel_id'] = system_channel
else:
fields['system_channel_id'] = system_channel.id
if 'owner' in fields:
if self.owner != self.me:
raise InvalidArgument('To transfer ownership you must be the owner of the guild.')
fields['owner_id'] = fields['owner'].id
if 'region' in fields:
fields['region'] = str(fields['region'])
level = fields.get('verification_level', self.verification_level)
if not isinstance(level, VerificationLevel):
raise InvalidArgument('verification_level field must be of type VerificationLevel')
fields['verification_level'] = level.value
explicit_content_filter = fields.get('explicit_content_filter', self.explicit_content_filter)
if not isinstance(explicit_content_filter, ContentFilter):
raise InvalidArgument('explicit_content_filter field must be of type ContentFilter')
fields['explicit_content_filter'] = explicit_content_filter.value
await http.edit_guild(self.id, reason=reason, **fields)
|
[
"async",
"def",
"edit",
"(",
"self",
",",
"*",
",",
"reason",
"=",
"None",
",",
"*",
"*",
"fields",
")",
":",
"http",
"=",
"self",
".",
"_state",
".",
"http",
"try",
":",
"icon_bytes",
"=",
"fields",
"[",
"'icon'",
"]",
"except",
"KeyError",
":",
"icon",
"=",
"self",
".",
"icon",
"else",
":",
"if",
"icon_bytes",
"is",
"not",
"None",
":",
"icon",
"=",
"utils",
".",
"_bytes_to_base64_data",
"(",
"icon_bytes",
")",
"else",
":",
"icon",
"=",
"None",
"try",
":",
"banner_bytes",
"=",
"fields",
"[",
"'banner'",
"]",
"except",
"KeyError",
":",
"banner",
"=",
"self",
".",
"banner",
"else",
":",
"if",
"banner_bytes",
"is",
"not",
"None",
":",
"banner",
"=",
"utils",
".",
"_bytes_to_base64_data",
"(",
"banner_bytes",
")",
"else",
":",
"banner",
"=",
"None",
"try",
":",
"vanity_code",
"=",
"fields",
"[",
"'vanity_code'",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"await",
"http",
".",
"change_vanity_code",
"(",
"self",
".",
"id",
",",
"vanity_code",
",",
"reason",
"=",
"reason",
")",
"try",
":",
"splash_bytes",
"=",
"fields",
"[",
"'splash'",
"]",
"except",
"KeyError",
":",
"splash",
"=",
"self",
".",
"splash",
"else",
":",
"if",
"splash_bytes",
"is",
"not",
"None",
":",
"splash",
"=",
"utils",
".",
"_bytes_to_base64_data",
"(",
"splash_bytes",
")",
"else",
":",
"splash",
"=",
"None",
"fields",
"[",
"'icon'",
"]",
"=",
"icon",
"fields",
"[",
"'banner'",
"]",
"=",
"banner",
"fields",
"[",
"'splash'",
"]",
"=",
"splash",
"try",
":",
"default_message_notifications",
"=",
"int",
"(",
"fields",
".",
"pop",
"(",
"'default_notifications'",
")",
")",
"except",
"(",
"TypeError",
",",
"KeyError",
")",
":",
"pass",
"else",
":",
"fields",
"[",
"'default_message_notifications'",
"]",
"=",
"default_message_notifications",
"try",
":",
"afk_channel",
"=",
"fields",
".",
"pop",
"(",
"'afk_channel'",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"afk_channel",
"is",
"None",
":",
"fields",
"[",
"'afk_channel_id'",
"]",
"=",
"afk_channel",
"else",
":",
"fields",
"[",
"'afk_channel_id'",
"]",
"=",
"afk_channel",
".",
"id",
"try",
":",
"system_channel",
"=",
"fields",
".",
"pop",
"(",
"'system_channel'",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"system_channel",
"is",
"None",
":",
"fields",
"[",
"'system_channel_id'",
"]",
"=",
"system_channel",
"else",
":",
"fields",
"[",
"'system_channel_id'",
"]",
"=",
"system_channel",
".",
"id",
"if",
"'owner'",
"in",
"fields",
":",
"if",
"self",
".",
"owner",
"!=",
"self",
".",
"me",
":",
"raise",
"InvalidArgument",
"(",
"'To transfer ownership you must be the owner of the guild.'",
")",
"fields",
"[",
"'owner_id'",
"]",
"=",
"fields",
"[",
"'owner'",
"]",
".",
"id",
"if",
"'region'",
"in",
"fields",
":",
"fields",
"[",
"'region'",
"]",
"=",
"str",
"(",
"fields",
"[",
"'region'",
"]",
")",
"level",
"=",
"fields",
".",
"get",
"(",
"'verification_level'",
",",
"self",
".",
"verification_level",
")",
"if",
"not",
"isinstance",
"(",
"level",
",",
"VerificationLevel",
")",
":",
"raise",
"InvalidArgument",
"(",
"'verification_level field must be of type VerificationLevel'",
")",
"fields",
"[",
"'verification_level'",
"]",
"=",
"level",
".",
"value",
"explicit_content_filter",
"=",
"fields",
".",
"get",
"(",
"'explicit_content_filter'",
",",
"self",
".",
"explicit_content_filter",
")",
"if",
"not",
"isinstance",
"(",
"explicit_content_filter",
",",
"ContentFilter",
")",
":",
"raise",
"InvalidArgument",
"(",
"'explicit_content_filter field must be of type ContentFilter'",
")",
"fields",
"[",
"'explicit_content_filter'",
"]",
"=",
"explicit_content_filter",
".",
"value",
"await",
"http",
".",
"edit_guild",
"(",
"self",
".",
"id",
",",
"reason",
"=",
"reason",
",",
"*",
"*",
"fields",
")"
] |
|coro|
Edits the guild.
You must have the :attr:`~Permissions.manage_guild` permission
to edit the guild.
Parameters
----------
name: :class:`str`
The new name of the guild.
description: :class:`str`
The new description of the guild. This is only available to guilds that
contain `VERIFIED` in :attr:`Guild.features`.
icon: :class:`bytes`
A :term:`py:bytes-like object` representing the icon. Only PNG/JPEG supported.
Could be ``None`` to denote removal of the icon.
banner: :class:`bytes`
A :term:`py:bytes-like object` representing the banner.
Could be ``None`` to denote removal of the banner.
splash: :class:`bytes`
A :term:`py:bytes-like object` representing the invite splash.
Only PNG/JPEG supported. Could be ``None`` to denote removing the
splash. Only available for partnered guilds with ``INVITE_SPLASH``
feature.
region: :class:`VoiceRegion`
The new region for the guild's voice communication.
afk_channel: Optional[:class:`VoiceChannel`]
The new channel that is the AFK channel. Could be ``None`` for no AFK channel.
afk_timeout: :class:`int`
The number of seconds until someone is moved to the AFK channel.
owner: :class:`Member`
The new owner of the guild to transfer ownership to. Note that you must
be owner of the guild to do this.
verification_level: :class:`VerificationLevel`
The new verification level for the guild.
default_notifications: :class:`NotificationLevel`
The new default notification level for the guild.
explicit_content_filter: :class:`ContentFilter`
The new explicit content filter for the guild.
vanity_code: :class:`str`
The new vanity code for the guild.
system_channel: Optional[:class:`TextChannel`]
The new channel that is used for the system channel. Could be ``None`` for no system channel.
reason: Optional[:class:`str`]
The reason for editing this guild. Shows up on the audit log.
Raises
-------
Forbidden
You do not have permissions to edit the guild.
HTTPException
Editing the guild failed.
InvalidArgument
The image format passed in to ``icon`` is invalid. It must be
PNG or JPG. This is also raised if you are not the owner of the
guild and request an ownership transfer.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L779-L928
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.fetch_member
|
async def fetch_member(self, member_id):
"""|coro|
Retreives a :class:`Member` from a guild ID, and a member ID.
.. note::
This method is an API call. For general usage, consider :meth:`get_member` instead.
Parameters
-----------
member_id: :class:`int`
The member's ID to fetch from.
Raises
-------
Forbidden
You do not have access to the guild.
HTTPException
Getting the guild failed.
Returns
--------
:class:`Member`
The member from the member ID.
"""
data = await self._state.http.get_member(self.id, member_id)
return Member(data=data, state=self._state, guild=self)
|
python
|
async def fetch_member(self, member_id):
"""|coro|
Retreives a :class:`Member` from a guild ID, and a member ID.
.. note::
This method is an API call. For general usage, consider :meth:`get_member` instead.
Parameters
-----------
member_id: :class:`int`
The member's ID to fetch from.
Raises
-------
Forbidden
You do not have access to the guild.
HTTPException
Getting the guild failed.
Returns
--------
:class:`Member`
The member from the member ID.
"""
data = await self._state.http.get_member(self.id, member_id)
return Member(data=data, state=self._state, guild=self)
|
[
"async",
"def",
"fetch_member",
"(",
"self",
",",
"member_id",
")",
":",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"get_member",
"(",
"self",
".",
"id",
",",
"member_id",
")",
"return",
"Member",
"(",
"data",
"=",
"data",
",",
"state",
"=",
"self",
".",
"_state",
",",
"guild",
"=",
"self",
")"
] |
|coro|
Retreives a :class:`Member` from a guild ID, and a member ID.
.. note::
This method is an API call. For general usage, consider :meth:`get_member` instead.
Parameters
-----------
member_id: :class:`int`
The member's ID to fetch from.
Raises
-------
Forbidden
You do not have access to the guild.
HTTPException
Getting the guild failed.
Returns
--------
:class:`Member`
The member from the member ID.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L930-L957
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.fetch_ban
|
async def fetch_ban(self, user):
"""|coro|
Retrieves the :class:`BanEntry` for a user, which is a namedtuple
with a ``user`` and ``reason`` field. See :meth:`bans` for more
information.
You must have the :attr:`~Permissions.ban_members` permission
to get this information.
Parameters
-----------
user: :class:`abc.Snowflake`
The user to get ban information from.
Raises
------
Forbidden
You do not have proper permissions to get the information.
NotFound
This user is not banned.
HTTPException
An error occurred while fetching the information.
Returns
-------
BanEntry
The BanEntry object for the specified user.
"""
data = await self._state.http.get_ban(user.id, self.id)
return BanEntry(
user=User(state=self._state, data=data['user']),
reason=data['reason']
)
|
python
|
async def fetch_ban(self, user):
"""|coro|
Retrieves the :class:`BanEntry` for a user, which is a namedtuple
with a ``user`` and ``reason`` field. See :meth:`bans` for more
information.
You must have the :attr:`~Permissions.ban_members` permission
to get this information.
Parameters
-----------
user: :class:`abc.Snowflake`
The user to get ban information from.
Raises
------
Forbidden
You do not have proper permissions to get the information.
NotFound
This user is not banned.
HTTPException
An error occurred while fetching the information.
Returns
-------
BanEntry
The BanEntry object for the specified user.
"""
data = await self._state.http.get_ban(user.id, self.id)
return BanEntry(
user=User(state=self._state, data=data['user']),
reason=data['reason']
)
|
[
"async",
"def",
"fetch_ban",
"(",
"self",
",",
"user",
")",
":",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"get_ban",
"(",
"user",
".",
"id",
",",
"self",
".",
"id",
")",
"return",
"BanEntry",
"(",
"user",
"=",
"User",
"(",
"state",
"=",
"self",
".",
"_state",
",",
"data",
"=",
"data",
"[",
"'user'",
"]",
")",
",",
"reason",
"=",
"data",
"[",
"'reason'",
"]",
")"
] |
|coro|
Retrieves the :class:`BanEntry` for a user, which is a namedtuple
with a ``user`` and ``reason`` field. See :meth:`bans` for more
information.
You must have the :attr:`~Permissions.ban_members` permission
to get this information.
Parameters
-----------
user: :class:`abc.Snowflake`
The user to get ban information from.
Raises
------
Forbidden
You do not have proper permissions to get the information.
NotFound
This user is not banned.
HTTPException
An error occurred while fetching the information.
Returns
-------
BanEntry
The BanEntry object for the specified user.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L959-L992
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.bans
|
async def bans(self):
"""|coro|
Retrieves all the users that are banned from the guild.
This coroutine returns a :class:`list` of BanEntry objects, which is a
namedtuple with a ``user`` field to denote the :class:`User`
that got banned along with a ``reason`` field specifying
why the user was banned that could be set to ``None``.
You must have the :attr:`~Permissions.ban_members` permission
to get this information.
Raises
-------
Forbidden
You do not have proper permissions to get the information.
HTTPException
An error occurred while fetching the information.
Returns
--------
List[BanEntry]
A list of BanEntry objects.
"""
data = await self._state.http.get_bans(self.id)
return [BanEntry(user=User(state=self._state, data=e['user']),
reason=e['reason'])
for e in data]
|
python
|
async def bans(self):
"""|coro|
Retrieves all the users that are banned from the guild.
This coroutine returns a :class:`list` of BanEntry objects, which is a
namedtuple with a ``user`` field to denote the :class:`User`
that got banned along with a ``reason`` field specifying
why the user was banned that could be set to ``None``.
You must have the :attr:`~Permissions.ban_members` permission
to get this information.
Raises
-------
Forbidden
You do not have proper permissions to get the information.
HTTPException
An error occurred while fetching the information.
Returns
--------
List[BanEntry]
A list of BanEntry objects.
"""
data = await self._state.http.get_bans(self.id)
return [BanEntry(user=User(state=self._state, data=e['user']),
reason=e['reason'])
for e in data]
|
[
"async",
"def",
"bans",
"(",
"self",
")",
":",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"get_bans",
"(",
"self",
".",
"id",
")",
"return",
"[",
"BanEntry",
"(",
"user",
"=",
"User",
"(",
"state",
"=",
"self",
".",
"_state",
",",
"data",
"=",
"e",
"[",
"'user'",
"]",
")",
",",
"reason",
"=",
"e",
"[",
"'reason'",
"]",
")",
"for",
"e",
"in",
"data",
"]"
] |
|coro|
Retrieves all the users that are banned from the guild.
This coroutine returns a :class:`list` of BanEntry objects, which is a
namedtuple with a ``user`` field to denote the :class:`User`
that got banned along with a ``reason`` field specifying
why the user was banned that could be set to ``None``.
You must have the :attr:`~Permissions.ban_members` permission
to get this information.
Raises
-------
Forbidden
You do not have proper permissions to get the information.
HTTPException
An error occurred while fetching the information.
Returns
--------
List[BanEntry]
A list of BanEntry objects.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L994-L1023
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.prune_members
|
async def prune_members(self, *, days, compute_prune_count=True, reason=None):
r"""|coro|
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
``days`` number of days and they have no roles.
You must have the :attr:`~Permissions.kick_members` permission
to use this.
To check how many members you would prune without actually pruning,
see the :meth:`estimate_pruned_members` function.
Parameters
-----------
days: :class:`int`
The number of days before counting as inactive.
reason: Optional[:class:`str`]
The reason for doing this action. Shows up on the audit log.
compute_prune_count: :class:`bool`
Whether to compute the prune count. This defaults to ``True``
which makes it prone to timeouts in very large guilds. In order
to prevent timeouts, you must set this to ``False``. If this is
set to ``False``\, then this function will always return ``None``.
Raises
-------
Forbidden
You do not have permissions to prune members.
HTTPException
An error occurred while pruning members.
InvalidArgument
An integer was not passed for ``days``.
Returns
---------
Optional[:class:`int`]
The number of members pruned. If ``compute_prune_count`` is ``False``
then this returns ``None``.
"""
if not isinstance(days, int):
raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days))
data = await self._state.http.prune_members(self.id, days, compute_prune_count=compute_prune_count, reason=reason)
return data['pruned']
|
python
|
async def prune_members(self, *, days, compute_prune_count=True, reason=None):
r"""|coro|
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
``days`` number of days and they have no roles.
You must have the :attr:`~Permissions.kick_members` permission
to use this.
To check how many members you would prune without actually pruning,
see the :meth:`estimate_pruned_members` function.
Parameters
-----------
days: :class:`int`
The number of days before counting as inactive.
reason: Optional[:class:`str`]
The reason for doing this action. Shows up on the audit log.
compute_prune_count: :class:`bool`
Whether to compute the prune count. This defaults to ``True``
which makes it prone to timeouts in very large guilds. In order
to prevent timeouts, you must set this to ``False``. If this is
set to ``False``\, then this function will always return ``None``.
Raises
-------
Forbidden
You do not have permissions to prune members.
HTTPException
An error occurred while pruning members.
InvalidArgument
An integer was not passed for ``days``.
Returns
---------
Optional[:class:`int`]
The number of members pruned. If ``compute_prune_count`` is ``False``
then this returns ``None``.
"""
if not isinstance(days, int):
raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days))
data = await self._state.http.prune_members(self.id, days, compute_prune_count=compute_prune_count, reason=reason)
return data['pruned']
|
[
"async",
"def",
"prune_members",
"(",
"self",
",",
"*",
",",
"days",
",",
"compute_prune_count",
"=",
"True",
",",
"reason",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"days",
",",
"int",
")",
":",
"raise",
"InvalidArgument",
"(",
"'Expected int for ``days``, received {0.__class__.__name__} instead.'",
".",
"format",
"(",
"days",
")",
")",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"prune_members",
"(",
"self",
".",
"id",
",",
"days",
",",
"compute_prune_count",
"=",
"compute_prune_count",
",",
"reason",
"=",
"reason",
")",
"return",
"data",
"[",
"'pruned'",
"]"
] |
r"""|coro|
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
``days`` number of days and they have no roles.
You must have the :attr:`~Permissions.kick_members` permission
to use this.
To check how many members you would prune without actually pruning,
see the :meth:`estimate_pruned_members` function.
Parameters
-----------
days: :class:`int`
The number of days before counting as inactive.
reason: Optional[:class:`str`]
The reason for doing this action. Shows up on the audit log.
compute_prune_count: :class:`bool`
Whether to compute the prune count. This defaults to ``True``
which makes it prone to timeouts in very large guilds. In order
to prevent timeouts, you must set this to ``False``. If this is
set to ``False``\, then this function will always return ``None``.
Raises
-------
Forbidden
You do not have permissions to prune members.
HTTPException
An error occurred while pruning members.
InvalidArgument
An integer was not passed for ``days``.
Returns
---------
Optional[:class:`int`]
The number of members pruned. If ``compute_prune_count`` is ``False``
then this returns ``None``.
|
[
"r",
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1025-L1071
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.estimate_pruned_members
|
async def estimate_pruned_members(self, *, days):
"""|coro|
Similar to :meth:`prune_members` except instead of actually
pruning members, it returns how many members it would prune
from the guild had it been called.
Parameters
-----------
days: :class:`int`
The number of days before counting as inactive.
Raises
-------
Forbidden
You do not have permissions to prune members.
HTTPException
An error occurred while fetching the prune members estimate.
InvalidArgument
An integer was not passed for ``days``.
Returns
---------
:class:`int`
The number of members estimated to be pruned.
"""
if not isinstance(days, int):
raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days))
data = await self._state.http.estimate_pruned_members(self.id, days)
return data['pruned']
|
python
|
async def estimate_pruned_members(self, *, days):
"""|coro|
Similar to :meth:`prune_members` except instead of actually
pruning members, it returns how many members it would prune
from the guild had it been called.
Parameters
-----------
days: :class:`int`
The number of days before counting as inactive.
Raises
-------
Forbidden
You do not have permissions to prune members.
HTTPException
An error occurred while fetching the prune members estimate.
InvalidArgument
An integer was not passed for ``days``.
Returns
---------
:class:`int`
The number of members estimated to be pruned.
"""
if not isinstance(days, int):
raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days))
data = await self._state.http.estimate_pruned_members(self.id, days)
return data['pruned']
|
[
"async",
"def",
"estimate_pruned_members",
"(",
"self",
",",
"*",
",",
"days",
")",
":",
"if",
"not",
"isinstance",
"(",
"days",
",",
"int",
")",
":",
"raise",
"InvalidArgument",
"(",
"'Expected int for ``days``, received {0.__class__.__name__} instead.'",
".",
"format",
"(",
"days",
")",
")",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"estimate_pruned_members",
"(",
"self",
".",
"id",
",",
"days",
")",
"return",
"data",
"[",
"'pruned'",
"]"
] |
|coro|
Similar to :meth:`prune_members` except instead of actually
pruning members, it returns how many members it would prune
from the guild had it been called.
Parameters
-----------
days: :class:`int`
The number of days before counting as inactive.
Raises
-------
Forbidden
You do not have permissions to prune members.
HTTPException
An error occurred while fetching the prune members estimate.
InvalidArgument
An integer was not passed for ``days``.
Returns
---------
:class:`int`
The number of members estimated to be pruned.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1094-L1125
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.invites
|
async def invites(self):
"""|coro|
Returns a list of all active instant invites from the guild.
You must have the :attr:`~Permissions.manage_guild` permission to get
this information.
Raises
-------
Forbidden
You do not have proper permissions to get the information.
HTTPException
An error occurred while fetching the information.
Returns
-------
List[:class:`Invite`]
The list of invites that are currently active.
"""
data = await self._state.http.invites_from(self.id)
result = []
for invite in data:
channel = self.get_channel(int(invite['channel']['id']))
invite['channel'] = channel
invite['guild'] = self
result.append(Invite(state=self._state, data=invite))
return result
|
python
|
async def invites(self):
"""|coro|
Returns a list of all active instant invites from the guild.
You must have the :attr:`~Permissions.manage_guild` permission to get
this information.
Raises
-------
Forbidden
You do not have proper permissions to get the information.
HTTPException
An error occurred while fetching the information.
Returns
-------
List[:class:`Invite`]
The list of invites that are currently active.
"""
data = await self._state.http.invites_from(self.id)
result = []
for invite in data:
channel = self.get_channel(int(invite['channel']['id']))
invite['channel'] = channel
invite['guild'] = self
result.append(Invite(state=self._state, data=invite))
return result
|
[
"async",
"def",
"invites",
"(",
"self",
")",
":",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"invites_from",
"(",
"self",
".",
"id",
")",
"result",
"=",
"[",
"]",
"for",
"invite",
"in",
"data",
":",
"channel",
"=",
"self",
".",
"get_channel",
"(",
"int",
"(",
"invite",
"[",
"'channel'",
"]",
"[",
"'id'",
"]",
")",
")",
"invite",
"[",
"'channel'",
"]",
"=",
"channel",
"invite",
"[",
"'guild'",
"]",
"=",
"self",
"result",
".",
"append",
"(",
"Invite",
"(",
"state",
"=",
"self",
".",
"_state",
",",
"data",
"=",
"invite",
")",
")",
"return",
"result"
] |
|coro|
Returns a list of all active instant invites from the guild.
You must have the :attr:`~Permissions.manage_guild` permission to get
this information.
Raises
-------
Forbidden
You do not have proper permissions to get the information.
HTTPException
An error occurred while fetching the information.
Returns
-------
List[:class:`Invite`]
The list of invites that are currently active.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1127-L1156
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.fetch_emojis
|
async def fetch_emojis(self):
r"""|coro|
Retrieves all custom :class:`Emoji`\s from the guild.
.. note::
This method is an API call. For general usage, consider :attr:`emojis` instead.
Raises
---------
HTTPException
An error occurred fetching the emojis.
Returns
--------
List[:class:`Emoji`]
The retrieved emojis.
"""
data = await self._state.http.get_all_custom_emojis(self.id)
return [Emoji(guild=self, state=self._state, data=d) for d in data]
|
python
|
async def fetch_emojis(self):
r"""|coro|
Retrieves all custom :class:`Emoji`\s from the guild.
.. note::
This method is an API call. For general usage, consider :attr:`emojis` instead.
Raises
---------
HTTPException
An error occurred fetching the emojis.
Returns
--------
List[:class:`Emoji`]
The retrieved emojis.
"""
data = await self._state.http.get_all_custom_emojis(self.id)
return [Emoji(guild=self, state=self._state, data=d) for d in data]
|
[
"async",
"def",
"fetch_emojis",
"(",
"self",
")",
":",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"get_all_custom_emojis",
"(",
"self",
".",
"id",
")",
"return",
"[",
"Emoji",
"(",
"guild",
"=",
"self",
",",
"state",
"=",
"self",
".",
"_state",
",",
"data",
"=",
"d",
")",
"for",
"d",
"in",
"data",
"]"
] |
r"""|coro|
Retrieves all custom :class:`Emoji`\s from the guild.
.. note::
This method is an API call. For general usage, consider :attr:`emojis` instead.
Raises
---------
HTTPException
An error occurred fetching the emojis.
Returns
--------
List[:class:`Emoji`]
The retrieved emojis.
|
[
"r",
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1158-L1178
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.fetch_emoji
|
async def fetch_emoji(self, emoji_id):
"""|coro|
Retrieves a custom :class:`Emoji` from the guild.
.. note::
This method is an API call.
For general usage, consider iterating over :attr:`emojis` instead.
Parameters
-------------
emoji_id: :class:`int`
The emoji's ID.
Raises
---------
NotFound
The emoji requested could not be found.
HTTPException
An error occurred fetching the emoji.
Returns
--------
:class:`Emoji`
The retrieved emoji.
"""
data = await self._state.http.get_custom_emoji(self.id, emoji_id)
return Emoji(guild=self, state=self._state, data=data)
|
python
|
async def fetch_emoji(self, emoji_id):
"""|coro|
Retrieves a custom :class:`Emoji` from the guild.
.. note::
This method is an API call.
For general usage, consider iterating over :attr:`emojis` instead.
Parameters
-------------
emoji_id: :class:`int`
The emoji's ID.
Raises
---------
NotFound
The emoji requested could not be found.
HTTPException
An error occurred fetching the emoji.
Returns
--------
:class:`Emoji`
The retrieved emoji.
"""
data = await self._state.http.get_custom_emoji(self.id, emoji_id)
return Emoji(guild=self, state=self._state, data=data)
|
[
"async",
"def",
"fetch_emoji",
"(",
"self",
",",
"emoji_id",
")",
":",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"get_custom_emoji",
"(",
"self",
".",
"id",
",",
"emoji_id",
")",
"return",
"Emoji",
"(",
"guild",
"=",
"self",
",",
"state",
"=",
"self",
".",
"_state",
",",
"data",
"=",
"data",
")"
] |
|coro|
Retrieves a custom :class:`Emoji` from the guild.
.. note::
This method is an API call.
For general usage, consider iterating over :attr:`emojis` instead.
Parameters
-------------
emoji_id: :class:`int`
The emoji's ID.
Raises
---------
NotFound
The emoji requested could not be found.
HTTPException
An error occurred fetching the emoji.
Returns
--------
:class:`Emoji`
The retrieved emoji.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1180-L1208
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.create_custom_emoji
|
async def create_custom_emoji(self, *, name, image, roles=None, reason=None):
r"""|coro|
Creates a custom :class:`Emoji` for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild,
unless the guild has the ``MORE_EMOJI`` feature which extends the limit to 200.
You must have the :attr:`~Permissions.manage_emojis` permission to
do this.
Parameters
-----------
name: :class:`str`
The emoji name. Must be at least 2 characters.
image: :class:`bytes`
The :term:`py:bytes-like object` representing the image data to use.
Only JPG, PNG and GIF images are supported.
roles: 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 creating this emoji. Shows up on the audit log.
Raises
-------
Forbidden
You are not allowed to create emojis.
HTTPException
An error occurred creating an emoji.
Returns
--------
:class:`Emoji`
The created emoji.
"""
img = utils._bytes_to_base64_data(image)
if roles:
roles = [role.id for role in roles]
data = await self._state.http.create_custom_emoji(self.id, name, img, roles=roles, reason=reason)
return self._state.store_emoji(self, data)
|
python
|
async def create_custom_emoji(self, *, name, image, roles=None, reason=None):
r"""|coro|
Creates a custom :class:`Emoji` for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild,
unless the guild has the ``MORE_EMOJI`` feature which extends the limit to 200.
You must have the :attr:`~Permissions.manage_emojis` permission to
do this.
Parameters
-----------
name: :class:`str`
The emoji name. Must be at least 2 characters.
image: :class:`bytes`
The :term:`py:bytes-like object` representing the image data to use.
Only JPG, PNG and GIF images are supported.
roles: 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 creating this emoji. Shows up on the audit log.
Raises
-------
Forbidden
You are not allowed to create emojis.
HTTPException
An error occurred creating an emoji.
Returns
--------
:class:`Emoji`
The created emoji.
"""
img = utils._bytes_to_base64_data(image)
if roles:
roles = [role.id for role in roles]
data = await self._state.http.create_custom_emoji(self.id, name, img, roles=roles, reason=reason)
return self._state.store_emoji(self, data)
|
[
"async",
"def",
"create_custom_emoji",
"(",
"self",
",",
"*",
",",
"name",
",",
"image",
",",
"roles",
"=",
"None",
",",
"reason",
"=",
"None",
")",
":",
"img",
"=",
"utils",
".",
"_bytes_to_base64_data",
"(",
"image",
")",
"if",
"roles",
":",
"roles",
"=",
"[",
"role",
".",
"id",
"for",
"role",
"in",
"roles",
"]",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"create_custom_emoji",
"(",
"self",
".",
"id",
",",
"name",
",",
"img",
",",
"roles",
"=",
"roles",
",",
"reason",
"=",
"reason",
")",
"return",
"self",
".",
"_state",
".",
"store_emoji",
"(",
"self",
",",
"data",
")"
] |
r"""|coro|
Creates a custom :class:`Emoji` for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild,
unless the guild has the ``MORE_EMOJI`` feature which extends the limit to 200.
You must have the :attr:`~Permissions.manage_emojis` permission to
do this.
Parameters
-----------
name: :class:`str`
The emoji name. Must be at least 2 characters.
image: :class:`bytes`
The :term:`py:bytes-like object` representing the image data to use.
Only JPG, PNG and GIF images are supported.
roles: 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 creating this emoji. Shows up on the audit log.
Raises
-------
Forbidden
You are not allowed to create emojis.
HTTPException
An error occurred creating an emoji.
Returns
--------
:class:`Emoji`
The created emoji.
|
[
"r",
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1210-L1250
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.create_role
|
async def create_role(self, *, reason=None, **fields):
"""|coro|
Creates a :class:`Role` for the guild.
All fields are optional.
You must have the :attr:`~Permissions.manage_roles` permission to
do this.
Parameters
-----------
name: :class:`str`
The role name. Defaults to 'new role'.
permissions: :class:`Permissions`
The permissions to have. Defaults to no permissions.
colour: :class:`Colour`
The colour for the role. Defaults to :meth:`Colour.default`.
This is aliased to ``color`` as well.
hoist: :class:`bool`
Indicates if the role should be shown separately in the member list.
Defaults to False.
mentionable: :class:`bool`
Indicates if the role should be mentionable by others.
Defaults to False.
reason: Optional[:class:`str`]
The reason for creating this role. Shows up on the audit log.
Raises
-------
Forbidden
You do not have permissions to create the role.
HTTPException
Creating the role failed.
InvalidArgument
An invalid keyword argument was given.
Returns
--------
:class:`Role`
The newly created role.
"""
try:
perms = fields.pop('permissions')
except KeyError:
fields['permissions'] = 0
else:
fields['permissions'] = perms.value
try:
colour = fields.pop('colour')
except KeyError:
colour = fields.get('color', Colour.default())
finally:
fields['color'] = colour.value
valid_keys = ('name', 'permissions', 'color', 'hoist', 'mentionable')
for key in fields:
if key not in valid_keys:
raise InvalidArgument('%r is not a valid field.' % key)
data = await self._state.http.create_role(self.id, reason=reason, **fields)
role = Role(guild=self, data=data, state=self._state)
# TODO: add to cache
return role
|
python
|
async def create_role(self, *, reason=None, **fields):
"""|coro|
Creates a :class:`Role` for the guild.
All fields are optional.
You must have the :attr:`~Permissions.manage_roles` permission to
do this.
Parameters
-----------
name: :class:`str`
The role name. Defaults to 'new role'.
permissions: :class:`Permissions`
The permissions to have. Defaults to no permissions.
colour: :class:`Colour`
The colour for the role. Defaults to :meth:`Colour.default`.
This is aliased to ``color`` as well.
hoist: :class:`bool`
Indicates if the role should be shown separately in the member list.
Defaults to False.
mentionable: :class:`bool`
Indicates if the role should be mentionable by others.
Defaults to False.
reason: Optional[:class:`str`]
The reason for creating this role. Shows up on the audit log.
Raises
-------
Forbidden
You do not have permissions to create the role.
HTTPException
Creating the role failed.
InvalidArgument
An invalid keyword argument was given.
Returns
--------
:class:`Role`
The newly created role.
"""
try:
perms = fields.pop('permissions')
except KeyError:
fields['permissions'] = 0
else:
fields['permissions'] = perms.value
try:
colour = fields.pop('colour')
except KeyError:
colour = fields.get('color', Colour.default())
finally:
fields['color'] = colour.value
valid_keys = ('name', 'permissions', 'color', 'hoist', 'mentionable')
for key in fields:
if key not in valid_keys:
raise InvalidArgument('%r is not a valid field.' % key)
data = await self._state.http.create_role(self.id, reason=reason, **fields)
role = Role(guild=self, data=data, state=self._state)
# TODO: add to cache
return role
|
[
"async",
"def",
"create_role",
"(",
"self",
",",
"*",
",",
"reason",
"=",
"None",
",",
"*",
"*",
"fields",
")",
":",
"try",
":",
"perms",
"=",
"fields",
".",
"pop",
"(",
"'permissions'",
")",
"except",
"KeyError",
":",
"fields",
"[",
"'permissions'",
"]",
"=",
"0",
"else",
":",
"fields",
"[",
"'permissions'",
"]",
"=",
"perms",
".",
"value",
"try",
":",
"colour",
"=",
"fields",
".",
"pop",
"(",
"'colour'",
")",
"except",
"KeyError",
":",
"colour",
"=",
"fields",
".",
"get",
"(",
"'color'",
",",
"Colour",
".",
"default",
"(",
")",
")",
"finally",
":",
"fields",
"[",
"'color'",
"]",
"=",
"colour",
".",
"value",
"valid_keys",
"=",
"(",
"'name'",
",",
"'permissions'",
",",
"'color'",
",",
"'hoist'",
",",
"'mentionable'",
")",
"for",
"key",
"in",
"fields",
":",
"if",
"key",
"not",
"in",
"valid_keys",
":",
"raise",
"InvalidArgument",
"(",
"'%r is not a valid field.'",
"%",
"key",
")",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"create_role",
"(",
"self",
".",
"id",
",",
"reason",
"=",
"reason",
",",
"*",
"*",
"fields",
")",
"role",
"=",
"Role",
"(",
"guild",
"=",
"self",
",",
"data",
"=",
"data",
",",
"state",
"=",
"self",
".",
"_state",
")",
"# TODO: add to cache",
"return",
"role"
] |
|coro|
Creates a :class:`Role` for the guild.
All fields are optional.
You must have the :attr:`~Permissions.manage_roles` permission to
do this.
Parameters
-----------
name: :class:`str`
The role name. Defaults to 'new role'.
permissions: :class:`Permissions`
The permissions to have. Defaults to no permissions.
colour: :class:`Colour`
The colour for the role. Defaults to :meth:`Colour.default`.
This is aliased to ``color`` as well.
hoist: :class:`bool`
Indicates if the role should be shown separately in the member list.
Defaults to False.
mentionable: :class:`bool`
Indicates if the role should be mentionable by others.
Defaults to False.
reason: Optional[:class:`str`]
The reason for creating this role. Shows up on the audit log.
Raises
-------
Forbidden
You do not have permissions to create the role.
HTTPException
Creating the role failed.
InvalidArgument
An invalid keyword argument was given.
Returns
--------
:class:`Role`
The newly created role.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1252-L1318
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.kick
|
async def kick(self, user, *, reason=None):
"""|coro|
Kicks a user from the guild.
The user must meet the :class:`abc.Snowflake` abc.
You must have the :attr:`~Permissions.kick_members` permission to
do this.
Parameters
-----------
user: :class:`abc.Snowflake`
The user to kick from their guild.
reason: Optional[:class:`str`]
The reason the user got kicked.
Raises
-------
Forbidden
You do not have the proper permissions to kick.
HTTPException
Kicking failed.
"""
await self._state.http.kick(user.id, self.id, reason=reason)
|
python
|
async def kick(self, user, *, reason=None):
"""|coro|
Kicks a user from the guild.
The user must meet the :class:`abc.Snowflake` abc.
You must have the :attr:`~Permissions.kick_members` permission to
do this.
Parameters
-----------
user: :class:`abc.Snowflake`
The user to kick from their guild.
reason: Optional[:class:`str`]
The reason the user got kicked.
Raises
-------
Forbidden
You do not have the proper permissions to kick.
HTTPException
Kicking failed.
"""
await self._state.http.kick(user.id, self.id, reason=reason)
|
[
"async",
"def",
"kick",
"(",
"self",
",",
"user",
",",
"*",
",",
"reason",
"=",
"None",
")",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"kick",
"(",
"user",
".",
"id",
",",
"self",
".",
"id",
",",
"reason",
"=",
"reason",
")"
] |
|coro|
Kicks a user from the guild.
The user must meet the :class:`abc.Snowflake` abc.
You must have the :attr:`~Permissions.kick_members` permission to
do this.
Parameters
-----------
user: :class:`abc.Snowflake`
The user to kick from their guild.
reason: Optional[:class:`str`]
The reason the user got kicked.
Raises
-------
Forbidden
You do not have the proper permissions to kick.
HTTPException
Kicking failed.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1320-L1344
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.ban
|
async def ban(self, user, *, reason=None, delete_message_days=1):
"""|coro|
Bans a user from the guild.
The user must meet the :class:`abc.Snowflake` abc.
You must have the :attr:`~Permissions.ban_members` permission to
do this.
Parameters
-----------
user: :class:`abc.Snowflake`
The user to ban from their guild.
delete_message_days: :class:`int`
The number of days worth of messages to delete from the user
in the guild. The minimum is 0 and the maximum is 7.
reason: Optional[:class:`str`]
The reason the user got banned.
Raises
-------
Forbidden
You do not have the proper permissions to ban.
HTTPException
Banning failed.
"""
await self._state.http.ban(user.id, self.id, delete_message_days, reason=reason)
|
python
|
async def ban(self, user, *, reason=None, delete_message_days=1):
"""|coro|
Bans a user from the guild.
The user must meet the :class:`abc.Snowflake` abc.
You must have the :attr:`~Permissions.ban_members` permission to
do this.
Parameters
-----------
user: :class:`abc.Snowflake`
The user to ban from their guild.
delete_message_days: :class:`int`
The number of days worth of messages to delete from the user
in the guild. The minimum is 0 and the maximum is 7.
reason: Optional[:class:`str`]
The reason the user got banned.
Raises
-------
Forbidden
You do not have the proper permissions to ban.
HTTPException
Banning failed.
"""
await self._state.http.ban(user.id, self.id, delete_message_days, reason=reason)
|
[
"async",
"def",
"ban",
"(",
"self",
",",
"user",
",",
"*",
",",
"reason",
"=",
"None",
",",
"delete_message_days",
"=",
"1",
")",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"ban",
"(",
"user",
".",
"id",
",",
"self",
".",
"id",
",",
"delete_message_days",
",",
"reason",
"=",
"reason",
")"
] |
|coro|
Bans a user from the guild.
The user must meet the :class:`abc.Snowflake` abc.
You must have the :attr:`~Permissions.ban_members` permission to
do this.
Parameters
-----------
user: :class:`abc.Snowflake`
The user to ban from their guild.
delete_message_days: :class:`int`
The number of days worth of messages to delete from the user
in the guild. The minimum is 0 and the maximum is 7.
reason: Optional[:class:`str`]
The reason the user got banned.
Raises
-------
Forbidden
You do not have the proper permissions to ban.
HTTPException
Banning failed.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1346-L1373
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.unban
|
async def unban(self, user, *, reason=None):
"""|coro|
Unbans a user from the guild.
The user must meet the :class:`abc.Snowflake` abc.
You must have the :attr:`~Permissions.ban_members` permission to
do this.
Parameters
-----------
user: :class:`abc.Snowflake`
The user to unban.
reason: Optional[:class:`str`]
The reason for doing this action. Shows up on the audit log.
Raises
-------
Forbidden
You do not have the proper permissions to unban.
HTTPException
Unbanning failed.
"""
await self._state.http.unban(user.id, self.id, reason=reason)
|
python
|
async def unban(self, user, *, reason=None):
"""|coro|
Unbans a user from the guild.
The user must meet the :class:`abc.Snowflake` abc.
You must have the :attr:`~Permissions.ban_members` permission to
do this.
Parameters
-----------
user: :class:`abc.Snowflake`
The user to unban.
reason: Optional[:class:`str`]
The reason for doing this action. Shows up on the audit log.
Raises
-------
Forbidden
You do not have the proper permissions to unban.
HTTPException
Unbanning failed.
"""
await self._state.http.unban(user.id, self.id, reason=reason)
|
[
"async",
"def",
"unban",
"(",
"self",
",",
"user",
",",
"*",
",",
"reason",
"=",
"None",
")",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"unban",
"(",
"user",
".",
"id",
",",
"self",
".",
"id",
",",
"reason",
"=",
"reason",
")"
] |
|coro|
Unbans a user from the guild.
The user must meet the :class:`abc.Snowflake` abc.
You must have the :attr:`~Permissions.ban_members` permission to
do this.
Parameters
-----------
user: :class:`abc.Snowflake`
The user to unban.
reason: Optional[:class:`str`]
The reason for doing this action. Shows up on the audit log.
Raises
-------
Forbidden
You do not have the proper permissions to unban.
HTTPException
Unbanning failed.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1375-L1399
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.vanity_invite
|
async def vanity_invite(self):
"""|coro|
Returns the guild's special vanity invite.
The guild must be partnered, i.e. have 'VANITY_URL' in
:attr:`~Guild.features`.
You must have the :attr:`~Permissions.manage_guild` permission to use
this as well.
Raises
-------
Forbidden
You do not have the proper permissions to get this.
HTTPException
Retrieving the vanity invite failed.
Returns
--------
:class:`Invite`
The special vanity invite.
"""
# we start with { code: abc }
payload = await self._state.http.get_vanity_code(self.id)
# get the vanity URL channel since default channels aren't
# reliable or a thing anymore
data = await self._state.http.get_invite(payload['code'])
payload['guild'] = self
payload['channel'] = self.get_channel(int(data['channel']['id']))
payload['revoked'] = False
payload['temporary'] = False
payload['max_uses'] = 0
payload['max_age'] = 0
return Invite(state=self._state, data=payload)
|
python
|
async def vanity_invite(self):
"""|coro|
Returns the guild's special vanity invite.
The guild must be partnered, i.e. have 'VANITY_URL' in
:attr:`~Guild.features`.
You must have the :attr:`~Permissions.manage_guild` permission to use
this as well.
Raises
-------
Forbidden
You do not have the proper permissions to get this.
HTTPException
Retrieving the vanity invite failed.
Returns
--------
:class:`Invite`
The special vanity invite.
"""
# we start with { code: abc }
payload = await self._state.http.get_vanity_code(self.id)
# get the vanity URL channel since default channels aren't
# reliable or a thing anymore
data = await self._state.http.get_invite(payload['code'])
payload['guild'] = self
payload['channel'] = self.get_channel(int(data['channel']['id']))
payload['revoked'] = False
payload['temporary'] = False
payload['max_uses'] = 0
payload['max_age'] = 0
return Invite(state=self._state, data=payload)
|
[
"async",
"def",
"vanity_invite",
"(",
"self",
")",
":",
"# we start with { code: abc }",
"payload",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"get_vanity_code",
"(",
"self",
".",
"id",
")",
"# get the vanity URL channel since default channels aren't",
"# reliable or a thing anymore",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"get_invite",
"(",
"payload",
"[",
"'code'",
"]",
")",
"payload",
"[",
"'guild'",
"]",
"=",
"self",
"payload",
"[",
"'channel'",
"]",
"=",
"self",
".",
"get_channel",
"(",
"int",
"(",
"data",
"[",
"'channel'",
"]",
"[",
"'id'",
"]",
")",
")",
"payload",
"[",
"'revoked'",
"]",
"=",
"False",
"payload",
"[",
"'temporary'",
"]",
"=",
"False",
"payload",
"[",
"'max_uses'",
"]",
"=",
"0",
"payload",
"[",
"'max_age'",
"]",
"=",
"0",
"return",
"Invite",
"(",
"state",
"=",
"self",
".",
"_state",
",",
"data",
"=",
"payload",
")"
] |
|coro|
Returns the guild's special vanity invite.
The guild must be partnered, i.e. have 'VANITY_URL' in
:attr:`~Guild.features`.
You must have the :attr:`~Permissions.manage_guild` permission to use
this as well.
Raises
-------
Forbidden
You do not have the proper permissions to get this.
HTTPException
Retrieving the vanity invite failed.
Returns
--------
:class:`Invite`
The special vanity invite.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1401-L1438
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.ack
|
def ack(self):
"""|coro|
Marks every message in this guild as read.
The user must not be a bot user.
Raises
-------
HTTPException
Acking failed.
ClientException
You must not be a bot user.
"""
state = self._state
if state.is_bot:
raise ClientException('Must not be a bot account to ack messages.')
return state.http.ack_guild(self.id)
|
python
|
def ack(self):
"""|coro|
Marks every message in this guild as read.
The user must not be a bot user.
Raises
-------
HTTPException
Acking failed.
ClientException
You must not be a bot user.
"""
state = self._state
if state.is_bot:
raise ClientException('Must not be a bot account to ack messages.')
return state.http.ack_guild(self.id)
|
[
"def",
"ack",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"_state",
"if",
"state",
".",
"is_bot",
":",
"raise",
"ClientException",
"(",
"'Must not be a bot account to ack messages.'",
")",
"return",
"state",
".",
"http",
".",
"ack_guild",
"(",
"self",
".",
"id",
")"
] |
|coro|
Marks every message in this guild as read.
The user must not be a bot user.
Raises
-------
HTTPException
Acking failed.
ClientException
You must not be a bot user.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1440-L1458
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.audit_logs
|
def audit_logs(self, *, limit=100, before=None, after=None, oldest_first=None, user=None, action=None):
"""Return an :class:`AsyncIterator` that enables receiving the guild's audit logs.
You must have the :attr:`~Permissions.view_audit_log` permission to use this.
Examples
----------
Getting the first 100 entries: ::
async for entry in guild.audit_logs(limit=100):
print('{0.user} did {0.action} to {0.target}'.format(entry))
Getting entries for a specific action: ::
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban):
print('{0.user} banned {0.target}'.format(entry))
Getting entries made by a specific user: ::
entries = await guild.audit_logs(limit=None, user=guild.me).flatten()
await channel.send('I made {} moderation actions.'.format(len(entries)))
Parameters
-----------
limit: Optional[:class:`int`]
The number of entries to retrieve. If ``None`` retrieve all entries.
before: Union[:class:`abc.Snowflake`, datetime]
Retrieve entries before this date or entry.
If a date is provided it must be a timezone-naive datetime representing UTC time.
after: Union[:class:`abc.Snowflake`, datetime]
Retrieve entries after this date or entry.
If a date is provided it must be a timezone-naive datetime representing UTC time.
oldest_first: :class:`bool`
If set to true, return entries in oldest->newest order. Defaults to True if
``after`` is specified, otherwise False.
user: :class:`abc.Snowflake`
The moderator to filter entries from.
action: :class:`AuditLogAction`
The action to filter with.
Raises
-------
Forbidden
You are not allowed to fetch audit logs
HTTPException
An error occurred while fetching the audit logs.
Yields
--------
:class:`AuditLogEntry`
The audit log entry.
"""
if user:
user = user.id
if action:
action = action.value
return AuditLogIterator(self, before=before, after=after, limit=limit,
oldest_first=oldest_first, user_id=user, action_type=action)
|
python
|
def audit_logs(self, *, limit=100, before=None, after=None, oldest_first=None, user=None, action=None):
"""Return an :class:`AsyncIterator` that enables receiving the guild's audit logs.
You must have the :attr:`~Permissions.view_audit_log` permission to use this.
Examples
----------
Getting the first 100 entries: ::
async for entry in guild.audit_logs(limit=100):
print('{0.user} did {0.action} to {0.target}'.format(entry))
Getting entries for a specific action: ::
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban):
print('{0.user} banned {0.target}'.format(entry))
Getting entries made by a specific user: ::
entries = await guild.audit_logs(limit=None, user=guild.me).flatten()
await channel.send('I made {} moderation actions.'.format(len(entries)))
Parameters
-----------
limit: Optional[:class:`int`]
The number of entries to retrieve. If ``None`` retrieve all entries.
before: Union[:class:`abc.Snowflake`, datetime]
Retrieve entries before this date or entry.
If a date is provided it must be a timezone-naive datetime representing UTC time.
after: Union[:class:`abc.Snowflake`, datetime]
Retrieve entries after this date or entry.
If a date is provided it must be a timezone-naive datetime representing UTC time.
oldest_first: :class:`bool`
If set to true, return entries in oldest->newest order. Defaults to True if
``after`` is specified, otherwise False.
user: :class:`abc.Snowflake`
The moderator to filter entries from.
action: :class:`AuditLogAction`
The action to filter with.
Raises
-------
Forbidden
You are not allowed to fetch audit logs
HTTPException
An error occurred while fetching the audit logs.
Yields
--------
:class:`AuditLogEntry`
The audit log entry.
"""
if user:
user = user.id
if action:
action = action.value
return AuditLogIterator(self, before=before, after=after, limit=limit,
oldest_first=oldest_first, user_id=user, action_type=action)
|
[
"def",
"audit_logs",
"(",
"self",
",",
"*",
",",
"limit",
"=",
"100",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
",",
"oldest_first",
"=",
"None",
",",
"user",
"=",
"None",
",",
"action",
"=",
"None",
")",
":",
"if",
"user",
":",
"user",
"=",
"user",
".",
"id",
"if",
"action",
":",
"action",
"=",
"action",
".",
"value",
"return",
"AuditLogIterator",
"(",
"self",
",",
"before",
"=",
"before",
",",
"after",
"=",
"after",
",",
"limit",
"=",
"limit",
",",
"oldest_first",
"=",
"oldest_first",
",",
"user_id",
"=",
"user",
",",
"action_type",
"=",
"action",
")"
] |
Return an :class:`AsyncIterator` that enables receiving the guild's audit logs.
You must have the :attr:`~Permissions.view_audit_log` permission to use this.
Examples
----------
Getting the first 100 entries: ::
async for entry in guild.audit_logs(limit=100):
print('{0.user} did {0.action} to {0.target}'.format(entry))
Getting entries for a specific action: ::
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban):
print('{0.user} banned {0.target}'.format(entry))
Getting entries made by a specific user: ::
entries = await guild.audit_logs(limit=None, user=guild.me).flatten()
await channel.send('I made {} moderation actions.'.format(len(entries)))
Parameters
-----------
limit: Optional[:class:`int`]
The number of entries to retrieve. If ``None`` retrieve all entries.
before: Union[:class:`abc.Snowflake`, datetime]
Retrieve entries before this date or entry.
If a date is provided it must be a timezone-naive datetime representing UTC time.
after: Union[:class:`abc.Snowflake`, datetime]
Retrieve entries after this date or entry.
If a date is provided it must be a timezone-naive datetime representing UTC time.
oldest_first: :class:`bool`
If set to true, return entries in oldest->newest order. Defaults to True if
``after`` is specified, otherwise False.
user: :class:`abc.Snowflake`
The moderator to filter entries from.
action: :class:`AuditLogAction`
The action to filter with.
Raises
-------
Forbidden
You are not allowed to fetch audit logs
HTTPException
An error occurred while fetching the audit logs.
Yields
--------
:class:`AuditLogEntry`
The audit log entry.
|
[
"Return",
"an",
":",
"class",
":",
"AsyncIterator",
"that",
"enables",
"receiving",
"the",
"guild",
"s",
"audit",
"logs",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1460-L1520
|
train
|
Rapptz/discord.py
|
discord/guild.py
|
Guild.widget
|
async def widget(self):
"""|coro|
Returns the widget of the guild.
.. note::
The guild must have the widget enabled to get this information.
Raises
-------
Forbidden
The widget for this guild is disabled.
HTTPException
Retrieving the widget failed.
Returns
--------
:class:`Widget`
The guild's widget.
"""
data = await self._state.http.get_widget(self.id)
return Widget(state=self._state, data=data)
|
python
|
async def widget(self):
"""|coro|
Returns the widget of the guild.
.. note::
The guild must have the widget enabled to get this information.
Raises
-------
Forbidden
The widget for this guild is disabled.
HTTPException
Retrieving the widget failed.
Returns
--------
:class:`Widget`
The guild's widget.
"""
data = await self._state.http.get_widget(self.id)
return Widget(state=self._state, data=data)
|
[
"async",
"def",
"widget",
"(",
"self",
")",
":",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"get_widget",
"(",
"self",
".",
"id",
")",
"return",
"Widget",
"(",
"state",
"=",
"self",
".",
"_state",
",",
"data",
"=",
"data",
")"
] |
|coro|
Returns the widget of the guild.
.. note::
The guild must have the widget enabled to get this information.
Raises
-------
Forbidden
The widget for this guild is disabled.
HTTPException
Retrieving the widget failed.
Returns
--------
:class:`Widget`
The guild's widget.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L1522-L1545
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.