text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
r"""A helper function that escapes Discord's markdown.
<END_TASK>
<USER_TASK:>
Description:
def escape_markdown(text, *, as_needed=False, ignore_links=True):
r"""A helper function that escapes Discord's markdown.
Parameters
-----------
text: :class:`str`
The text to escape markdown from.
as_needed: :class:`bool`
Whether to escape the markdown characters as needed. This
means that it does not escape extraneous characters if it's
not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**``
instead of ``\*\*hello\*\*``. Note however that this can open
you up to some clever syntax abuse. Defaults to ``False``.
ignore_links: :class:`bool`
Whether to leave links alone when escaping markdown. For example,
if a URL in the text contains characters such as ``_`` then it will
be left alone. This option is not supported with ``as_needed``.
Defaults to ``True``.
Returns
--------
:class:`str`
The text with the markdown special characters escaped with a slash.
""" |
if not as_needed:
url_regex = r'(?P<url>(?:https?|steam)://(?:-\.)?(?:[^\s/?\.#-]+\.?)+(?:/[^\s]*)?)'
def replacement(match):
groupdict = match.groupdict()
is_url = groupdict.get('url')
if is_url:
return is_url
return '\\' + groupdict['markdown']
regex = r'(?P<markdown>[_\\~|\*`])'
if ignore_links:
regex = '(?:%s|%s)' % (url_regex, regex)
return re.sub(regex, replacement, text)
else:
text = re.sub(r'\\', r'\\\\', text)
return _MARKDOWN_ESCAPE_REGEX.sub(r'\\\1', text) |
<SYSTEM_TASK:>
Adds two numbers together.
<END_TASK>
<USER_TASK:>
Description:
async def add(ctx, left: int, right: int):
"""Adds two numbers together.""" |
await ctx.send(left + right) |
<SYSTEM_TASK:>
Repeats a message multiple times.
<END_TASK>
<USER_TASK:>
Description:
async def repeat(ctx, times: int, content='repeating...'):
"""Repeats a message multiple times.""" |
for i in range(times):
await ctx.send(content) |
<SYSTEM_TASK:>
Plays a file from the local filesystem
<END_TASK>
<USER_TASK:>
Description:
async def play(self, ctx, *, query):
"""Plays a file from the local filesystem""" |
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send('Now playing: {}'.format(query)) |
<SYSTEM_TASK:>
Changes the player's volume
<END_TASK>
<USER_TASK:>
Description:
async def volume(self, ctx, volume: int):
"""Changes the player's volume""" |
if ctx.voice_client is None:
return await ctx.send("Not connected to a voice channel.")
ctx.voice_client.source.volume = volume / 100
await ctx.send("Changed volume to {}%".format(volume)) |
<SYSTEM_TASK:>
Queries the duration of the call.
<END_TASK>
<USER_TASK:>
Description:
def duration(self):
"""Queries the duration of the call.
If the call has not ended then the current duration will
be returned.
Returns
---------
datetime.timedelta
The timedelta object representing the duration.
""" |
if self.ended_timestamp is None:
return datetime.datetime.utcnow() - self.message.created_at
else:
return self.ended_timestamp - self.message.created_at |
<SYSTEM_TASK:>
Returns a friendly URL version of the avatar the webhook has.
<END_TASK>
<USER_TASK:>
Description:
def avatar_url_as(self, *, format=None, size=1024):
"""Returns a friendly URL version of the avatar the webhook has.
If the webhook does not have a traditional avatar, their default
avatar URL is returned instead.
The format must be one of 'jpeg', 'jpg', or 'png'.
The size must be a power of 2 between 16 and 1024.
Parameters
-----------
format: Optional[:class:`str`]
The format to attempt to convert the avatar to.
If the format is ``None``, then it is equivalent to png.
size: :class:`int`
The size of the image to display.
Raises
------
InvalidArgument
Bad image format passed to ``format`` or invalid ``size``.
Returns
--------
:class:`Asset`
The resulting CDN asset.
""" |
if self.avatar is None:
# Default is always blurple apparently
return Asset(self._state, 'https://cdn.discordapp.com/embed/avatars/0.png')
if not utils.valid_icon_size(size):
raise InvalidArgument("size must be a power of 2 between 16 and 1024")
format = format or 'png'
if format not in ('png', 'jpg', 'jpeg'):
raise InvalidArgument("format must be one of 'png', 'jpg', or 'jpeg'.")
url = 'https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.{1}?size={2}'.format(self, format, size)
return Asset(self._state, url) |
<SYSTEM_TASK:>
Returns the channel-specific overwrites for a member or a role.
<END_TASK>
<USER_TASK:>
Description:
def overwrites_for(self, obj):
"""Returns the channel-specific overwrites for a member or a role.
Parameters
-----------
obj
The :class:`Role` or :class:`abc.User` denoting
whose overwrite to get.
Returns
---------
:class:`PermissionOverwrite`
The permission overwrites for this object.
""" |
if isinstance(obj, User):
predicate = lambda p: p.type == 'member'
elif isinstance(obj, Role):
predicate = lambda p: p.type == 'role'
else:
predicate = lambda p: True
for overwrite in filter(predicate, self._overwrites):
if overwrite.id == obj.id:
allow = Permissions(overwrite.allow)
deny = Permissions(overwrite.deny)
return PermissionOverwrite.from_pair(allow, deny)
return PermissionOverwrite() |
<SYSTEM_TASK:>
Returns all of the channel's overwrites.
<END_TASK>
<USER_TASK:>
Description:
def overwrites(self):
"""Returns all of the channel's overwrites.
This is returned as a dictionary where the key contains the target which
can be either a :class:`Role` or a :class:`Member` and the key is the
overwrite as a :class:`PermissionOverwrite`.
Returns
--------
Mapping[Union[:class:`Role`, :class:`Member`], :class:`PermissionOverwrite`]:
The channel's permission overwrites.
""" |
ret = {}
for ow in self._overwrites:
allow = Permissions(ow.allow)
deny = Permissions(ow.deny)
overwrite = PermissionOverwrite.from_pair(allow, deny)
if ow.type == 'role':
target = self.guild.get_role(ow.id)
elif ow.type == 'member':
target = self.guild.get_member(ow.id)
# TODO: There is potential data loss here in the non-chunked
# case, i.e. target is None because get_member returned nothing.
# This can be fixed with a slight breaking change to the return type,
# i.e. adding discord.Object to the list of it
# However, for now this is an acceptable compromise.
if target is not None:
ret[target] = overwrite
return ret |
<SYSTEM_TASK:>
A decorator that schedules a task in the background for you with
<END_TASK>
<USER_TASK:>
Description:
def loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None):
"""A decorator that schedules a task in the background for you with
optional reconnect logic.
Parameters
------------
seconds: :class:`float`
The number of seconds between every iteration.
minutes: :class:`float`
The number of minutes between every iteration.
hours: :class:`float`
The number of hours between every iteration.
count: Optional[:class:`int`]
The number of loops to do, ``None`` if it should be an
infinite loop.
reconnect: :class:`bool`
Whether to handle errors and restart the task
using an exponential back-off algorithm similar to the
one used in :meth:`discord.Client.connect`.
loop: :class:`asyncio.AbstractEventLoop`
The loop to use to register the task, if not given
defaults to :func:`asyncio.get_event_loop`.
Raises
--------
ValueError
An invalid value was given.
TypeError
The function was not a coroutine.
Returns
---------
:class:`Loop`
The loop helper that handles the background task.
""" |
def decorator(func):
return Loop(func, seconds=seconds, minutes=minutes, hours=hours,
count=count, reconnect=reconnect, loop=loop)
return decorator |
<SYSTEM_TASK:>
Removes an exception type from being handled during the reconnect logic.
<END_TASK>
<USER_TASK:>
Description:
def remove_exception_type(self, exc):
"""Removes an exception type from being handled during the reconnect logic.
Parameters
------------
exc: Type[:class:`BaseException`]
The exception class to handle.
Returns
---------
:class:`bool`
Whether it was successfully removed.
""" |
old_length = len(self._valid_exception)
self._valid_exception = tuple(x for x in self._valid_exception if x is not exc)
return len(self._valid_exception) != old_length |
<SYSTEM_TASK:>
A function that also acts as a decorator to register a coroutine to be
<END_TASK>
<USER_TASK:>
Description:
def after_loop(self, coro):
"""A function that also acts as a decorator to register a coroutine to be
called after the loop finished running.
Parameters
------------
coro: :term:`py:awaitable`
The coroutine to register after the loop finishes.
Raises
-------
TypeError
The function was not a coroutine.
""" |
if not (inspect.iscoroutinefunction(coro) or inspect.isawaitable(coro)):
raise TypeError('Expected coroutine or awaitable, received {0.__name__!r}.'.format(type(coro)))
self._after_loop = coro |
<SYSTEM_TASK:>
Compute the next delay
<END_TASK>
<USER_TASK:>
Description:
def delay(self):
"""Compute the next delay
Returns the next delay to wait according to the exponential
backoff algorithm. This is a value between 0 and base * 2^exp
where exponent starts off at 1 and is incremented at every
invocation of this method up to a maximum of 10.
If a period of more than base * 2^11 has passed since the last
retry, the exponent is reset to 1.
""" |
invocation = time.monotonic()
interval = invocation - self._last_invocation
self._last_invocation = invocation
if interval > self._reset_time:
self._exp = 0
self._exp = min(self._exp + 1, self._max)
return self._randfunc(0, self._base * 2 ** self._exp) |
<SYSTEM_TASK:>
Returns True if self has the same or fewer permissions as other.
<END_TASK>
<USER_TASK:>
Description:
def is_subset(self, other):
"""Returns True if self has the same or fewer permissions as other.""" |
if isinstance(other, Permissions):
return (self.value & other.value) == self.value
else:
raise TypeError("cannot compare {} with {}".format(self.__class__.__name__, other.__class__.__name__)) |
<SYSTEM_TASK:>
r"""Bulk updates this permission object.
<END_TASK>
<USER_TASK:>
Description:
def update(self, **kwargs):
r"""Bulk updates this permission object.
Allows you to set multiple attributes by using keyword
arguments. The names must be equivalent to the properties
listed. Extraneous key/value pairs will be silently ignored.
Parameters
------------
\*\*kwargs
A list of key/value pairs to bulk update permissions with.
""" |
for key, value in kwargs.items():
try:
is_property = isinstance(getattr(self.__class__, key), property)
except AttributeError:
continue
if is_property:
setattr(self, key, value) |
<SYSTEM_TASK:>
Retrieves the parameter OrderedDict without the context or self parameters.
<END_TASK>
<USER_TASK:>
Description:
def clean_params(self):
"""Retrieves the parameter OrderedDict without the context or self parameters.
Useful for inspecting signature.
""" |
result = self.params.copy()
if self.cog is not None:
# first parameter is self
result.popitem(last=False)
try:
# first/second parameter is context
result.popitem(last=False)
except Exception:
raise ValueError('Missing context parameter') from None
return result |
<SYSTEM_TASK:>
Retrieves the fully qualified parent command name.
<END_TASK>
<USER_TASK:>
Description:
def full_parent_name(self):
"""Retrieves the fully qualified parent command name.
This the base command name required to execute it. For example,
in ``?one two three`` the parent name would be ``one two``.
""" |
entries = []
command = self
while command.parent is not None:
command = command.parent
entries.append(command.name)
return ' '.join(reversed(entries)) |
<SYSTEM_TASK:>
Retrieves the parents of this command.
<END_TASK>
<USER_TASK:>
Description:
def parents(self):
"""Retrieves the parents of this command.
If the command has no parents then it returns an empty :class:`list`.
For example in commands ``?a b c test``, the parents are ``[c, b, a]``.
.. versionadded:: 1.1.0
""" |
entries = []
command = self
while command.parent is not None:
command = command.parent
entries.append(command)
return entries |
<SYSTEM_TASK:>
Retrieves the fully qualified command name.
<END_TASK>
<USER_TASK:>
Description:
def qualified_name(self):
"""Retrieves the fully qualified command name.
This is the full parent name with the command name as well.
For example, in ``?one two three`` the qualified name would be
``one two three``.
""" |
parent = self.full_parent_name
if parent:
return parent + ' ' + self.name
else:
return self.name |
<SYSTEM_TASK:>
Checks whether the command is currently on cooldown.
<END_TASK>
<USER_TASK:>
Description:
def is_on_cooldown(self, ctx):
"""Checks whether the command is currently on cooldown.
Parameters
-----------
ctx: :class:`.Context.`
The invocation context to use when checking the commands cooldown status.
Returns
--------
:class:`bool`
A boolean indicating if the command is on cooldown.
""" |
if not self._buckets.valid:
return False
bucket = self._buckets.get_bucket(ctx.message)
return bucket.get_tokens() == 0 |
<SYSTEM_TASK:>
Resets the cooldown on this command.
<END_TASK>
<USER_TASK:>
Description:
def reset_cooldown(self, ctx):
"""Resets the cooldown on this command.
Parameters
-----------
ctx: :class:`.Context`
The invocation context to reset the cooldown under.
""" |
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx.message)
bucket.reset() |
<SYSTEM_TASK:>
A decorator that registers a coroutine as a local error handler.
<END_TASK>
<USER_TASK:>
Description:
def error(self, coro):
"""A decorator that registers a coroutine as a local error handler.
A local error handler is an :func:`.on_command_error` event limited to
a single command. However, the :func:`.on_command_error` is still
invoked afterwards as the catch-all.
Parameters
-----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the local error handler.
Raises
-------
TypeError
The coroutine passed is not actually a coroutine.
""" |
if not asyncio.iscoroutinefunction(coro):
raise TypeError('The error handler must be a coroutine.')
self.on_error = coro
return coro |
<SYSTEM_TASK:>
A decorator that registers a coroutine as a pre-invoke hook.
<END_TASK>
<USER_TASK:>
Description:
def before_invoke(self, coro):
"""A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is
called. This makes it a useful function to set up database
connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.before_invoke` for more info.
Parameters
-----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the pre-invoke hook.
Raises
-------
TypeError
The coroutine passed is not actually a coroutine.
""" |
if not asyncio.iscoroutinefunction(coro):
raise TypeError('The pre-invoke hook must be a coroutine.')
self._before_invoke = coro
return coro |
<SYSTEM_TASK:>
A decorator that registers a coroutine as a post-invoke hook.
<END_TASK>
<USER_TASK:>
Description:
def after_invoke(self, coro):
"""A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is
called. This makes it a useful function to clean-up database
connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.after_invoke` for more info.
Parameters
-----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the post-invoke hook.
Raises
-------
TypeError
The coroutine passed is not actually a coroutine.
""" |
if not asyncio.iscoroutinefunction(coro):
raise TypeError('The post-invoke hook must be a coroutine.')
self._after_invoke = coro
return coro |
<SYSTEM_TASK:>
Gets the "short" documentation of a command.
<END_TASK>
<USER_TASK:>
Description:
def short_doc(self):
"""Gets the "short" documentation of a command.
By default, this is the :attr:`brief` attribute.
If that lookup leads to an empty string then the first line of the
:attr:`help` attribute is used instead.
""" |
if self.brief is not None:
return self.brief
if self.help is not None:
return self.help.split('\n', 1)[0]
return '' |
<SYSTEM_TASK:>
Returns a POSIX-like signature useful for help command output.
<END_TASK>
<USER_TASK:>
Description:
def signature(self):
"""Returns a POSIX-like signature useful for help command output.""" |
if self.usage is not None:
return self.usage
params = self.clean_params
if not params:
return ''
result = []
for name, param in params.items():
greedy = isinstance(param.annotation, converters._Greedy)
if param.default is not param.empty:
# We don't want None or '' to trigger the [name=value] case and instead it should
# do [name] since [name=None] or [name=] are not exactly useful for the user.
should_print = param.default if isinstance(param.default, str) else param.default is not None
if should_print:
result.append('[%s=%s]' % (name, param.default) if not greedy else
'[%s=%s]...' % (name, param.default))
continue
else:
result.append('[%s]' % name)
elif param.kind == param.VAR_POSITIONAL:
result.append('[%s...]' % name)
elif greedy:
result.append('[%s]...' % name)
elif self._is_typing_optional(param.annotation):
result.append('[%s]' % name)
else:
result.append('<%s>' % name)
return ' '.join(result) |
<SYSTEM_TASK:>
An iterator that recursively walks through all commands and subcommands.
<END_TASK>
<USER_TASK:>
Description:
def walk_commands(self):
"""An iterator that recursively walks through all commands and subcommands.""" |
for command in tuple(self.all_commands.values()):
yield command
if isinstance(command, GroupMixin):
yield from command.walk_commands() |
<SYSTEM_TASK:>
Waits for a DISPATCH'd event that meets the predicate.
<END_TASK>
<USER_TASK:>
Description:
def wait_for(self, event, predicate, result=None):
"""Waits for a DISPATCH'd event that meets the predicate.
Parameters
-----------
event: :class:`str`
The event name in all upper case to wait for.
predicate
A function that takes a data parameter to check for event
properties. The data parameter is the 'd' key in the JSON message.
result
A function that takes the same data parameter and executes to send
the result to the future. If None, returns the data.
Returns
--------
asyncio.Future
A future to wait for.
""" |
future = self.loop.create_future()
entry = EventListener(event=event, predicate=predicate, result=result, future=future)
self._dispatch_listeners.append(entry)
return future |
<SYSTEM_TASK:>
Polls for a DISPATCH event and handles the general gateway loop.
<END_TASK>
<USER_TASK:>
Description:
async def poll_event(self):
"""Polls for a DISPATCH event and handles the general gateway loop.
Raises
------
ConnectionClosed
The websocket connection was terminated for unhandled reasons.
""" |
try:
msg = await self.recv()
await self.received_message(msg)
except websockets.exceptions.ConnectionClosed as exc:
if self._can_handle_close(exc.code):
log.info('Websocket closed with %s (%s), attempting a reconnect.', exc.code, exc.reason)
raise ResumeWebSocket(self.shard_id) from exc
else:
log.info('Websocket closed with %s (%s), cannot reconnect.', exc.code, exc.reason)
raise ConnectionClosed(exc, shard_id=self.shard_id) from exc |
<SYSTEM_TASK:>
Clears the paginator to have no pages.
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
"""Clears the paginator to have no pages.""" |
if self.prefix is not None:
self._current_page = [self.prefix]
self._count = len(self.prefix) + 1 # prefix + newline
else:
self._current_page = []
self._count = 0
self._pages = [] |
<SYSTEM_TASK:>
Adds a line to the current page.
<END_TASK>
<USER_TASK:>
Description:
def add_line(self, line='', *, empty=False):
"""Adds a line to the current page.
If the line exceeds the :attr:`max_size` then an exception
is raised.
Parameters
-----------
line: :class:`str`
The line to add.
empty: :class:`bool`
Indicates if another empty line should be added.
Raises
------
RuntimeError
The line was too big for the current :attr:`max_size`.
""" |
max_page_size = self.max_size - self._prefix_len - 2
if len(line) > max_page_size:
raise RuntimeError('Line exceeds maximum page size %s' % (max_page_size))
if self._count + len(line) + 1 > self.max_size:
self.close_page()
self._count += len(line) + 1
self._current_page.append(line)
if empty:
self._current_page.append('')
self._count += 1 |
<SYSTEM_TASK:>
Prematurely terminate a page.
<END_TASK>
<USER_TASK:>
Description:
def close_page(self):
"""Prematurely terminate a page.""" |
if self.suffix is not None:
self._current_page.append(self.suffix)
self._pages.append('\n'.join(self._current_page))
if self.prefix is not None:
self._current_page = [self.prefix]
self._count = len(self.prefix) + 1 # prefix + newline
else:
self._current_page = []
self._count = 0 |
<SYSTEM_TASK:>
The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
<END_TASK>
<USER_TASK:>
Description:
def clean_prefix(self):
"""The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.""" |
user = self.context.guild.me if self.context.guild else self.context.bot.user
# this breaks if the prefix mention is not the bot itself but I
# consider this to be an *incredibly* strange use case. I'd rather go
# for this common use case rather than waste performance for the
# odd one.
return self.context.prefix.replace(user.mention, '@' + user.display_name) |
<SYSTEM_TASK:>
Retrieves the signature portion of the help page.
<END_TASK>
<USER_TASK:>
Description:
def get_command_signature(self, command):
"""Retrieves the signature portion of the help page.
Parameters
------------
command: :class:`Command`
The command to get the signature of.
Returns
--------
:class:`str`
The signature for the command.
""" |
parent = command.full_parent_name
if len(command.aliases) > 0:
aliases = '|'.join(command.aliases)
fmt = '[%s|%s]' % (command.name, aliases)
if parent:
fmt = parent + ' ' + fmt
alias = fmt
else:
alias = command.name if not parent else parent + ' ' + command.name
return '%s%s %s' % (self.clean_prefix, alias, command.signature) |
<SYSTEM_TASK:>
Removes mentions from the string to prevent abuse.
<END_TASK>
<USER_TASK:>
Description:
def remove_mentions(self, string):
"""Removes mentions from the string to prevent abuse.
This includes ``@everyone``, ``@here``, member mentions and role mentions.
""" |
def replace(obj, *, transforms=self.MENTION_TRANSFORMS):
return transforms.get(obj.group(0), '@invalid')
return self.MENTION_PATTERN.sub(replace, string) |
<SYSTEM_TASK:>
Returns the largest name length of the specified command list.
<END_TASK>
<USER_TASK:>
Description:
def get_max_size(self, commands):
"""Returns the largest name length of the specified command list.
Parameters
------------
commands: Sequence[:class:`Command`]
A sequence of commands to check for the largest size.
Returns
--------
:class:`int`
The maximum width of the commands.
""" |
as_lengths = (
discord.utils._string_width(c.name)
for c in commands
)
return max(as_lengths, default=0) |
<SYSTEM_TASK:>
Indents a list of commands after the specified heading.
<END_TASK>
<USER_TASK:>
Description:
def add_indented_commands(self, commands, *, heading, max_size=None):
"""Indents a list of commands after the specified heading.
The formatting is added to the :attr:`paginator`.
The default implementation is the command name indented by
:attr:`indent` spaces, padded to ``max_size`` followed by
the command's :attr:`Command.short_doc` and then shortened
to fit into the :attr:`width`.
Parameters
-----------
commands: Sequence[:class:`Command`]
A list of commands to indent for output.
heading: :class:`str`
The heading to add to the output. This is only added
if the list of commands is greater than 0.
max_size: Optional[:class:`int`]
The max size to use for the gap between indents.
If unspecified, calls :meth:`get_max_size` on the
commands parameter.
""" |
if not commands:
return
self.paginator.add_line(heading)
max_size = max_size or self.get_max_size(commands)
get_width = discord.utils._string_width
for command in commands:
name = command.name
width = max_size - (get_width(name) - len(name))
entry = '{0}{1:<{width}} {2}'.format(self.indent * ' ', name, command.short_doc, width=width)
self.paginator.add_line(self.shorten_text(entry)) |
<SYSTEM_TASK:>
Adds the minified bot heading with commands to the output.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Adds formatting information on a subcommand.
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Adds the formatting information on a command's aliases.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
A utility function to format commands and groups.
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Sends an audio packet composed of the data.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Clears the internal state of the bot.
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
A blocking call that abstracts away the event loop
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
A decorator that registers an event to listen to.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
A property that returns an array of role IDs matched with
<END_TASK>
<USER_TASK:>
Description:
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)] |
<SYSTEM_TASK:>
A callable that implements when mentioned or other prefixes provided.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Adds a global check to the bot.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Removes a global check from the bot.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Removes a listener from the pool of listeners.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Adds a "cog" to the bot.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Removes a cog from the bot.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Loads an extension.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Unloads an extension.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Atomically reloads an extension.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Returns a boolean indicating if the guild is "chunked".
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Returns the shard ID for this guild if applicable.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Returns the first member found that matches the name provided.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Create a list of blueprints, optionally grouping them under a
<END_TASK>
<USER_TASK:>
Description:
def group(*blueprints, url_prefix=""):
"""
Create a list of blueprints, optionally grouping them under a
general URL prefix.
:param blueprints: blueprints to be registered as a group
:param url_prefix: URL route to be prepended to all sub-prefixes
""" |
def chain(nested):
"""itertools.chain() but leaves strings untouched"""
for i in nested:
if isinstance(i, (list, tuple)):
yield from chain(i)
elif isinstance(i, BlueprintGroup):
yield from i.blueprints
else:
yield i
bps = BlueprintGroup(url_prefix=url_prefix)
for bp in chain(blueprints):
if bp.url_prefix is None:
bp.url_prefix = ""
bp.url_prefix = url_prefix + bp.url_prefix
bps.append(bp)
return bps |
<SYSTEM_TASK:>
Register the blueprint to the sanic app.
<END_TASK>
<USER_TASK:>
Description:
def register(self, app, options):
"""
Register the blueprint to the sanic app.
:param app: Instance of :class:`sanic.app.Sanic` class
:param options: Options to be used while registering the
blueprint into the app.
*url_prefix* - URL Prefix to override the blueprint prefix
""" |
url_prefix = options.get("url_prefix", self.url_prefix)
# Routes
for future in self.routes:
# attach the blueprint name to the handler so that it can be
# prefixed properly in the router
future.handler.__blueprintname__ = self.name
# Prepend the blueprint URI prefix if available
uri = url_prefix + future.uri if url_prefix else future.uri
version = future.version or self.version
app.route(
uri=uri[1:] if uri.startswith("//") else uri,
methods=future.methods,
host=future.host or self.host,
strict_slashes=future.strict_slashes,
stream=future.stream,
version=version,
name=future.name,
)(future.handler)
for future in self.websocket_routes:
# attach the blueprint name to the handler so that it can be
# prefixed properly in the router
future.handler.__blueprintname__ = self.name
# Prepend the blueprint URI prefix if available
uri = url_prefix + future.uri if url_prefix else future.uri
app.websocket(
uri=uri,
host=future.host or self.host,
strict_slashes=future.strict_slashes,
name=future.name,
)(future.handler)
# Middleware
for future in self.middlewares:
if future.args or future.kwargs:
app.register_middleware(
future.middleware, *future.args, **future.kwargs
)
else:
app.register_middleware(future.middleware)
# Exceptions
for future in self.exceptions:
app.exception(*future.args, **future.kwargs)(future.handler)
# Static Files
for future in self.statics:
# Prepend the blueprint URI prefix if available
uri = url_prefix + future.uri if url_prefix else future.uri
app.static(
uri, future.file_or_directory, *future.args, **future.kwargs
)
# Event listeners
for event, listeners in self.listeners.items():
for listener in listeners:
app.listener(event)(listener) |
<SYSTEM_TASK:>
Create a blueprint route from a decorated function.
<END_TASK>
<USER_TASK:>
Description:
def route(
self,
uri,
methods=frozenset({"GET"}),
host=None,
strict_slashes=None,
stream=False,
version=None,
name=None,
):
"""Create a blueprint route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:param methods: list of acceptable HTTP methods.
:param host: IP Address of FQDN for the sanic server to use.
:param strict_slashes: Enforce the API urls are requested with a
training */*
:param stream: If the route should provide a streaming support
:param version: Blueprint Version
:param name: Unique name to identify the Route
:return a decorated method that when invoked will return an object
of type :class:`FutureRoute`
""" |
if strict_slashes is None:
strict_slashes = self.strict_slashes
def decorator(handler):
route = FutureRoute(
handler,
uri,
methods,
host,
strict_slashes,
stream,
version,
name,
)
self.routes.append(route)
return handler
return decorator |
<SYSTEM_TASK:>
Create a blueprint websocket route from a decorated function.
<END_TASK>
<USER_TASK:>
Description:
def websocket(
self, uri, host=None, strict_slashes=None, version=None, name=None
):
"""Create a blueprint websocket route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:param host: IP Address of FQDN for the sanic server to use.
:param strict_slashes: Enforce the API urls are requested with a
training */*
:param version: Blueprint Version
:param name: Unique name to identify the Websocket Route
""" |
if strict_slashes is None:
strict_slashes = self.strict_slashes
def decorator(handler):
route = FutureRoute(
handler, uri, [], host, strict_slashes, False, version, name
)
self.websocket_routes.append(route)
return handler
return decorator |
<SYSTEM_TASK:>
Create a blueprint websocket route from a function.
<END_TASK>
<USER_TASK:>
Description:
def add_websocket_route(
self, handler, uri, host=None, version=None, name=None
):
"""Create a blueprint websocket route from a function.
:param handler: function for handling uri requests. Accepts function,
or class instance with a view_class method.
:param uri: endpoint at which the route will be accessible.
:param host: IP Address of FQDN for the sanic server to use.
:param version: Blueprint Version
:param name: Unique name to identify the Websocket Route
:return: function or class instance
""" |
self.websocket(uri=uri, host=host, version=version, name=name)(handler)
return handler |
<SYSTEM_TASK:>
Create a listener from a decorated function.
<END_TASK>
<USER_TASK:>
Description:
def listener(self, event):
"""Create a listener from a decorated function.
:param event: Event to listen to.
""" |
def decorator(listener):
self.listeners[event].append(listener)
return listener
return decorator |
<SYSTEM_TASK:>
Create a blueprint middleware from a decorated function.
<END_TASK>
<USER_TASK:>
Description:
def middleware(self, *args, **kwargs):
"""
Create a blueprint middleware from a decorated function.
:param args: Positional arguments to be used while invoking the
middleware
:param kwargs: optional keyword args that can be used with the
middleware.
""" |
def register_middleware(_middleware):
future_middleware = FutureMiddleware(_middleware, args, kwargs)
self.middlewares.append(future_middleware)
return _middleware
# Detect which way this was called, @middleware or @middleware('AT')
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
middleware = args[0]
args = []
return register_middleware(middleware)
else:
if kwargs.get("bp_group") and callable(args[0]):
middleware = args[0]
args = args[1:]
kwargs.pop("bp_group")
return register_middleware(middleware)
else:
return register_middleware |
<SYSTEM_TASK:>
This method enables the process of creating a global exception
<END_TASK>
<USER_TASK:>
Description:
def exception(self, *args, **kwargs):
"""
This method enables the process of creating a global exception
handler for the current blueprint under question.
:param args: List of Python exceptions to be caught by the handler
:param kwargs: Additional optional arguments to be passed to the
exception handler
:return a decorated method to handle global exceptions for any
route registered under this blueprint.
""" |
def decorator(handler):
exception = FutureException(handler, args, kwargs)
self.exceptions.append(exception)
return handler
return decorator |
<SYSTEM_TASK:>
Raise an exception based on SanicException. Returns the HTTP response
<END_TASK>
<USER_TASK:>
Description:
def abort(status_code, message=None):
"""
Raise an exception based on SanicException. Returns the HTTP response
message appropriate for the given status code, unless provided.
:param status_code: The HTTP status code to return.
:param message: The HTTP response body. Defaults to the messages
in response.py for the given status code.
""" |
if message is None:
message = STATUS_CODES.get(status_code)
# These are stored as bytes in the STATUS_CODES dict
message = message.decode("utf8")
sanic_exception = _sanic_exceptions.get(status_code, SanicException)
raise sanic_exception(message=message, status_code=status_code) |
<SYSTEM_TASK:>
Schedule a task to run later, after the loop has started.
<END_TASK>
<USER_TASK:>
Description:
def add_task(self, task):
"""Schedule a task to run later, after the loop has started.
Different from asyncio.ensure_future in that it does not
also return a future, and the actual ensure_future call
is delayed until before server start.
:param task: future, couroutine or awaitable
""" |
try:
if callable(task):
try:
self.loop.create_task(task(self))
except TypeError:
self.loop.create_task(task())
else:
self.loop.create_task(task)
except SanicException:
@self.listener("before_server_start")
def run(app, loop):
if callable(task):
try:
loop.create_task(task(self))
except TypeError:
loop.create_task(task())
else:
loop.create_task(task) |
<SYSTEM_TASK:>
A helper method to register a function as a websocket route.
<END_TASK>
<USER_TASK:>
Description:
def add_websocket_route(
self,
handler,
uri,
host=None,
strict_slashes=None,
subprotocols=None,
name=None,
):
"""
A helper method to register a function as a websocket route.
:param handler: a callable function or instance of a class
that can handle the websocket request
:param host: Host IP or FQDN details
:param uri: URL path that will be mapped to the websocket
handler
:param strict_slashes: If the API endpoint needs to terminate
with a "/" or not
:param subprotocols: Subprotocols to be used with websocket
handshake
:param name: A unique name assigned to the URL so that it can
be used with :func:`url_for`
:return: Objected decorated by :func:`websocket`
""" |
if strict_slashes is None:
strict_slashes = self.strict_slashes
return self.websocket(
uri,
host=host,
strict_slashes=strict_slashes,
subprotocols=subprotocols,
name=name,
)(handler) |
<SYSTEM_TASK:>
Enable or disable the support for websocket.
<END_TASK>
<USER_TASK:>
Description:
def enable_websocket(self, enable=True):
"""Enable or disable the support for websocket.
Websocket is enabled automatically if websocket routes are
added to the application.
""" |
if not self.websocket_enabled:
# if the server is stopped, we want to cancel any ongoing
# websocket tasks, to allow the server to exit promptly
@self.listener("before_server_stop")
def cancel_websocket_tasks(app, loop):
for task in self.websocket_tasks:
task.cancel()
self.websocket_enabled = enable |
<SYSTEM_TASK:>
Decorate a function to be registered as a handler for exceptions
<END_TASK>
<USER_TASK:>
Description:
def exception(self, *exceptions):
"""Decorate a function to be registered as a handler for exceptions
:param exceptions: exceptions
:return: decorated function
""" |
def response(handler):
for exception in exceptions:
if isinstance(exception, (tuple, list)):
for e in exception:
self.error_handler.add(e, handler)
else:
self.error_handler.add(exception, handler)
return handler
return response |
<SYSTEM_TASK:>
Register an application level middleware that will be attached
<END_TASK>
<USER_TASK:>
Description:
def register_middleware(self, middleware, attach_to="request"):
"""
Register an application level middleware that will be attached
to all the API URLs registered under this application.
This method is internally invoked by the :func:`middleware`
decorator provided at the app level.
:param middleware: Callback method to be attached to the
middleware
:param attach_to: The state at which the middleware needs to be
invoked in the lifecycle of an *HTTP Request*.
**request** - Invoke before the request is processed
**response** - Invoke before the response is returned back
:return: decorated method
""" |
if attach_to == "request":
if middleware not in self.request_middleware:
self.request_middleware.append(middleware)
if attach_to == "response":
if middleware not in self.response_middleware:
self.response_middleware.appendleft(middleware)
return middleware |
<SYSTEM_TASK:>
Take a request from the HTTP Server and return a response object
<END_TASK>
<USER_TASK:>
Description:
async def handle_request(self, request, write_callback, stream_callback):
"""Take a request from the HTTP Server and return a response object
to be sent back The HTTP Server only expects a response object, so
exception handling must be done here
:param request: HTTP Request object
:param write_callback: Synchronous response function to be
called with the response as the only argument
:param stream_callback: Coroutine that handles streaming a
StreamingHTTPResponse if produced by the handler.
:return: Nothing
""" |
# Define `response` var here to remove warnings about
# allocation before assignment below.
response = None
cancelled = False
try:
# -------------------------------------------- #
# Request Middleware
# -------------------------------------------- #
response = await self._run_request_middleware(request)
# No middleware results
if not response:
# -------------------------------------------- #
# Execute Handler
# -------------------------------------------- #
# Fetch handler from router
handler, args, kwargs, uri = self.router.get(request)
request.uri_template = uri
if handler is None:
raise ServerError(
(
"'None' was returned while requesting a "
"handler from the router"
)
)
else:
if not getattr(handler, "__blueprintname__", False):
request.endpoint = self._build_endpoint_name(
handler.__name__
)
else:
request.endpoint = self._build_endpoint_name(
getattr(handler, "__blueprintname__", ""),
handler.__name__,
)
# Run response handler
response = handler(request, *args, **kwargs)
if isawaitable(response):
response = await response
except CancelledError:
# If response handler times out, the server handles the error
# and cancels the handle_request job.
# In this case, the transport is already closed and we cannot
# issue a response.
response = None
cancelled = True
except Exception as e:
# -------------------------------------------- #
# Response Generation Failed
# -------------------------------------------- #
try:
response = self.error_handler.response(request, e)
if isawaitable(response):
response = await response
except Exception as e:
if isinstance(e, SanicException):
response = self.error_handler.default(
request=request, exception=e
)
elif self.debug:
response = HTTPResponse(
"Error while handling error: {}\nStack: {}".format(
e, format_exc()
),
status=500,
)
else:
response = HTTPResponse(
"An error occurred while handling an error", status=500
)
finally:
# -------------------------------------------- #
# Response Middleware
# -------------------------------------------- #
# Don't run response middleware if response is None
if response is not None:
try:
response = await self._run_response_middleware(
request, response
)
except CancelledError:
# Response middleware can timeout too, as above.
response = None
cancelled = True
except BaseException:
error_logger.exception(
"Exception occurred in one of response "
"middleware handlers"
)
if cancelled:
raise CancelledError()
# pass the response to the correct callback
if isinstance(response, StreamingHTTPResponse):
await stream_callback(response)
else:
write_callback(response) |
<SYSTEM_TASK:>
Run the HTTP Server and listen until keyboard interrupt or term
<END_TASK>
<USER_TASK:>
Description:
def run(
self,
host: Optional[str] = None,
port: Optional[int] = None,
debug: bool = False,
ssl: Union[dict, SSLContext, None] = None,
sock: Optional[socket] = None,
workers: int = 1,
protocol: Type[Protocol] = None,
backlog: int = 100,
stop_event: Any = None,
register_sys_signals: bool = True,
access_log: Optional[bool] = None,
**kwargs: Any
) -> None:
"""Run the HTTP Server and listen until keyboard interrupt or term
signal. On termination, drain connections before closing.
:param host: Address to host on
:type host: str
:param port: Port to host on
:type port: int
:param debug: Enables debug output (slows server)
:type debug: bool
:param ssl: SSLContext, or location of certificate and key
for SSL encryption of worker(s)
:type ssl:SSLContext or dict
:param sock: Socket for the server to accept connections from
:type sock: socket
:param workers: Number of processes received before it is respected
:type workers: int
:param protocol: Subclass of asyncio Protocol class
:type protocol: type[Protocol]
:param backlog: a number of unaccepted connections that the system
will allow before refusing new connections
:type backlog: int
:param stop_event: event to be triggered
before stopping the app - deprecated
:type stop_event: None
:param register_sys_signals: Register SIG* events
:type register_sys_signals: bool
:param access_log: Enables writing access logs (slows server)
:type access_log: bool
:return: Nothing
""" |
if "loop" in kwargs:
raise TypeError(
"loop is not a valid argument. To use an existing loop, "
"change to create_server().\nSee more: "
"https://sanic.readthedocs.io/en/latest/sanic/deploying.html"
"#asynchronous-support"
)
# Default auto_reload to false
auto_reload = False
# If debug is set, default it to true (unless on windows)
if debug and os.name == "posix":
auto_reload = True
# Allow for overriding either of the defaults
auto_reload = kwargs.get("auto_reload", auto_reload)
if sock is None:
host, port = host or "127.0.0.1", port or 8000
if protocol is None:
protocol = (
WebSocketProtocol if self.websocket_enabled else HttpProtocol
)
if stop_event is not None:
if debug:
warnings.simplefilter("default")
warnings.warn(
"stop_event will be removed from future versions.",
DeprecationWarning,
)
# if access_log is passed explicitly change config.ACCESS_LOG
if access_log is not None:
self.config.ACCESS_LOG = access_log
server_settings = self._helper(
host=host,
port=port,
debug=debug,
ssl=ssl,
sock=sock,
workers=workers,
protocol=protocol,
backlog=backlog,
register_sys_signals=register_sys_signals,
auto_reload=auto_reload,
)
try:
self.is_running = True
if workers == 1:
if auto_reload and os.name != "posix":
# This condition must be removed after implementing
# auto reloader for other operating systems.
raise NotImplementedError
if (
auto_reload
and os.environ.get("SANIC_SERVER_RUNNING") != "true"
):
reloader_helpers.watchdog(2)
else:
serve(**server_settings)
else:
serve_multiple(server_settings, workers)
except BaseException:
error_logger.exception(
"Experienced exception while trying to serve"
)
raise
finally:
self.is_running = False
logger.info("Server Stopped") |
<SYSTEM_TASK:>
Returns response object with body in json format.
<END_TASK>
<USER_TASK:>
Description:
def json(
body,
status=200,
headers=None,
content_type="application/json",
dumps=json_dumps,
**kwargs
):
"""
Returns response object with body in json format.
:param body: Response data to be serialized.
:param status: Response code.
:param headers: Custom Headers.
:param kwargs: Remaining arguments that are passed to the json encoder.
""" |
return HTTPResponse(
dumps(body, **kwargs),
headers=headers,
status=status,
content_type=content_type,
) |
<SYSTEM_TASK:>
Returns response object with body in text format.
<END_TASK>
<USER_TASK:>
Description:
def text(
body, status=200, headers=None, content_type="text/plain; charset=utf-8"
):
"""
Returns response object with body in text format.
:param body: Response data to be encoded.
:param status: Response code.
:param headers: Custom Headers.
:param content_type: the content type (string) of the response
""" |
return HTTPResponse(
body, status=status, headers=headers, content_type=content_type
) |
<SYSTEM_TASK:>
Return a streaming response object with file data.
<END_TASK>
<USER_TASK:>
Description:
async def file_stream(
location,
status=200,
chunk_size=4096,
mime_type=None,
headers=None,
filename=None,
_range=None,
):
"""Return a streaming response object with file data.
:param location: Location of file on system.
:param chunk_size: The size of each chunk in the stream (in bytes)
:param mime_type: Specific mime_type.
:param headers: Custom Headers.
:param filename: Override filename.
:param _range:
""" |
headers = headers or {}
if filename:
headers.setdefault(
"Content-Disposition", 'attachment; filename="{}"'.format(filename)
)
filename = filename or path.split(location)[-1]
_file = await open_async(location, mode="rb")
async def _streaming_fn(response):
nonlocal _file, chunk_size
try:
if _range:
chunk_size = min((_range.size, chunk_size))
await _file.seek(_range.start)
to_send = _range.size
while to_send > 0:
content = await _file.read(chunk_size)
if len(content) < 1:
break
to_send -= len(content)
await response.write(content)
else:
while True:
content = await _file.read(chunk_size)
if len(content) < 1:
break
await response.write(content)
finally:
await _file.close()
return # Returning from this fn closes the stream
mime_type = mime_type or guess_type(filename)[0] or "text/plain"
if _range:
headers["Content-Range"] = "bytes %s-%s/%s" % (
_range.start,
_range.end,
_range.total,
)
status = 206
return StreamingHTTPResponse(
streaming_fn=_streaming_fn,
status=status,
headers=headers,
content_type=mime_type,
) |
<SYSTEM_TASK:>
Accepts an coroutine `streaming_fn` which can be used to
<END_TASK>
<USER_TASK:>
Description:
def stream(
streaming_fn,
status=200,
headers=None,
content_type="text/plain; charset=utf-8",
):
"""Accepts an coroutine `streaming_fn` which can be used to
write chunks to a streaming response. Returns a `StreamingHTTPResponse`.
Example usage::
@app.route("/")
async def index(request):
async def streaming_fn(response):
await response.write('foo')
await response.write('bar')
return stream(streaming_fn, content_type='text/plain')
:param streaming_fn: A coroutine accepts a response and
writes content to that response.
:param mime_type: Specific mime_type.
:param headers: Custom Headers.
""" |
return StreamingHTTPResponse(
streaming_fn, headers=headers, content_type=content_type, status=status
) |
<SYSTEM_TASK:>
Writes a chunk of data to the streaming response.
<END_TASK>
<USER_TASK:>
Description:
async def write(self, data):
"""Writes a chunk of data to the streaming response.
:param data: bytes-ish data to be written.
""" |
if type(data) != bytes:
data = self._encode_body(data)
self.protocol.push_data(b"%x\r\n%b\r\n" % (len(data), data))
await self.protocol.drain() |
<SYSTEM_TASK:>
Streams headers, runs the `streaming_fn` callback that writes
<END_TASK>
<USER_TASK:>
Description:
async def stream(
self, version="1.1", keep_alive=False, keep_alive_timeout=None
):
"""Streams headers, runs the `streaming_fn` callback that writes
content to the response body, then finalizes the response body.
""" |
headers = self.get_headers(
version,
keep_alive=keep_alive,
keep_alive_timeout=keep_alive_timeout,
)
self.protocol.push_data(headers)
await self.protocol.drain()
await self.streaming_fn(self)
self.protocol.push_data(b"0\r\n\r\n") |
<SYSTEM_TASK:>
The Abstract class `MutableSequence` leverages this insert method to
<END_TASK>
<USER_TASK:>
Description:
def insert(self, index: int, item: object) -> None:
"""
The Abstract class `MutableSequence` leverages this insert method to
perform the `BlueprintGroup.append` operation.
:param index: Index to use for removing a new Blueprint item
:param item: New `Blueprint` object.
:return: None
""" |
self._blueprints.insert(index, item) |
<SYSTEM_TASK:>
A decorator that can be used to implement a Middleware plugin to
<END_TASK>
<USER_TASK:>
Description:
def middleware(self, *args, **kwargs):
"""
A decorator that can be used to implement a Middleware plugin to
all of the Blueprints that belongs to this specific Blueprint Group.
In case of nested Blueprint Groups, the same middleware is applied
across each of the Blueprints recursively.
:param args: Optional positional Parameters to be use middleware
:param kwargs: Optional Keyword arg to use with Middleware
:return: Partial function to apply the middleware
""" |
kwargs["bp_group"] = True
def register_middleware_for_blueprints(fn):
for blueprint in self.blueprints:
blueprint.middleware(fn, *args, **kwargs)
return register_middleware_for_blueprints |
<SYSTEM_TASK:>
Check if elapsed time since last response exceeds our configured
<END_TASK>
<USER_TASK:>
Description:
def keep_alive_timeout_callback(self):
"""
Check if elapsed time since last response exceeds our configured
maximum keep alive timeout value and if so, close the transport
pipe and let the response writer handle the error.
:return: None
""" |
time_elapsed = time() - self._last_response_time
if time_elapsed < self.keep_alive_timeout:
time_left = self.keep_alive_timeout - time_elapsed
self._keep_alive_timeout_handler = self.loop.call_later(
time_left, self.keep_alive_timeout_callback
)
else:
logger.debug("KeepAlive Timeout. Closing connection.")
self.transport.close()
self.transport = None |
<SYSTEM_TASK:>
Writes response content synchronously to the transport.
<END_TASK>
<USER_TASK:>
Description:
def write_response(self, response):
"""
Writes response content synchronously to the transport.
""" |
if self._response_timeout_handler:
self._response_timeout_handler.cancel()
self._response_timeout_handler = None
try:
keep_alive = self.keep_alive
self.transport.write(
response.output(
self.request.version, keep_alive, self.keep_alive_timeout
)
)
self.log_response(response)
except AttributeError:
logger.error(
"Invalid response object for url %s, "
"Expected Type: HTTPResponse, Actual Type: %s",
self.url,
type(response),
)
self.write_error(ServerError("Invalid response type"))
except RuntimeError:
if self._debug:
logger.error(
"Connection lost before response written @ %s",
self.request.ip,
)
keep_alive = False
except Exception as e:
self.bail_out(
"Writing response failed, connection closed {}".format(repr(e))
)
finally:
if not keep_alive:
self.transport.close()
self.transport = None
else:
self._keep_alive_timeout_handler = self.loop.call_later(
self.keep_alive_timeout, self.keep_alive_timeout_callback
)
self._last_response_time = time()
self.cleanup() |
<SYSTEM_TASK:>
In case if the transport pipes are closed and the sanic app encounters
<END_TASK>
<USER_TASK:>
Description:
def bail_out(self, message, from_error=False):
"""
In case if the transport pipes are closed and the sanic app encounters
an error while writing data to the transport pipe, we log the error
with proper details.
:param message: Error message to display
:param from_error: If the bail out was invoked while handling an
exception scenario.
:type message: str
:type from_error: bool
:return: None
""" |
if from_error or self.transport is None or self.transport.is_closing():
logger.error(
"Transport closed @ %s and exception "
"experienced during error handling",
(
self.transport.get_extra_info("peername")
if self.transport is not None
else "N/A"
),
)
logger.debug("Exception:", exc_info=True)
else:
self.write_error(ServerError(message))
logger.error(message) |
<SYSTEM_TASK:>
This is called when KeepAlive feature is used,
<END_TASK>
<USER_TASK:>
Description:
def cleanup(self):
"""This is called when KeepAlive feature is used,
it resets the connection in order for it to be able
to handle receiving another request on the same connection.""" |
self.parser = None
self.request = None
self.url = None
self.headers = None
self._request_handler_task = None
self._request_stream_task = None
self._total_request_size = 0
self._is_stream_handler = False |
<SYSTEM_TASK:>
Stop reading when gets None
<END_TASK>
<USER_TASK:>
Description:
async def read(self):
""" Stop reading when gets None """ |
payload = await self._queue.get()
self._queue.task_done()
return payload |
<SYSTEM_TASK:>
Attempt to return the original client ip based on X-Forwarded-For
<END_TASK>
<USER_TASK:>
Description:
def remote_addr(self):
"""Attempt to return the original client ip based on X-Forwarded-For
or X-Real-IP. If HTTP headers are unavailable or untrusted, returns
an empty string.
:return: original client ip.
""" |
if not hasattr(self, "_remote_addr"):
if self.app.config.PROXIES_COUNT == 0:
self._remote_addr = ""
elif self.app.config.REAL_IP_HEADER and self.headers.get(
self.app.config.REAL_IP_HEADER
):
self._remote_addr = self.headers[
self.app.config.REAL_IP_HEADER
]
elif self.app.config.FORWARDED_FOR_HEADER:
forwarded_for = self.headers.get(
self.app.config.FORWARDED_FOR_HEADER, ""
).split(",")
remote_addrs = [
addr
for addr in [addr.strip() for addr in forwarded_for]
if addr
]
if self.app.config.PROXIES_COUNT == -1:
self._remote_addr = remote_addrs[0]
elif len(remote_addrs) >= self.app.config.PROXIES_COUNT:
self._remote_addr = remote_addrs[
-self.app.config.PROXIES_COUNT
]
else:
self._remote_addr = ""
else:
self._remote_addr = ""
return self._remote_addr |
<SYSTEM_TASK:>
This function was borrowed from distutils.utils. While distutils
<END_TASK>
<USER_TASK:>
Description:
def strtobool(val):
"""
This function was borrowed from distutils.utils. While distutils
is part of stdlib, it feels odd to use distutils in main application code.
The function was modified to walk its talk and actually return bool
and not int.
""" |
val = val.lower()
if val in ("y", "yes", "t", "true", "on", "1"):
return True
elif val in ("n", "no", "f", "false", "off", "0"):
return False
else:
raise ValueError("invalid truth value %r" % (val,)) |
<SYSTEM_TASK:>
Load a configuration from an environment variable pointing to
<END_TASK>
<USER_TASK:>
Description:
def from_envvar(self, variable_name):
"""Load a configuration from an environment variable pointing to
a configuration file.
:param variable_name: name of the environment variable
:return: bool. ``True`` if able to load config, ``False`` otherwise.
""" |
config_file = os.environ.get(variable_name)
if not config_file:
raise RuntimeError(
"The environment variable %r is not set and "
"thus configuration could not be loaded." % variable_name
)
return self.from_pyfile(config_file) |
<SYSTEM_TASK:>
Update the values from the given object.
<END_TASK>
<USER_TASK:>
Description:
def from_object(self, obj):
"""Update the values from the given object.
Objects are usually either modules or classes.
Just the uppercase variables in that object are stored in the config.
Example usage::
from yourapplication import default_config
app.config.from_object(default_config)
You should not use this function to load the actual configuration but
rather configuration defaults. The actual config should be loaded
with :meth:`from_pyfile` and ideally from a location not within the
package because the package might be installed system wide.
:param obj: an object holding the configuration
""" |
for key in dir(obj):
if key.isupper():
self[key] = getattr(obj, key) |
<SYSTEM_TASK:>
Looks for prefixed environment variables and applies
<END_TASK>
<USER_TASK:>
Description:
def load_environment_vars(self, prefix=SANIC_PREFIX):
"""
Looks for prefixed environment variables and applies
them to the configuration if present.
""" |
for k, v in os.environ.items():
if k.startswith(prefix):
_, config_key = k.split(prefix, 1)
try:
self[config_key] = int(v)
except ValueError:
try:
self[config_key] = float(v)
except ValueError:
try:
self[config_key] = strtobool(v)
except ValueError:
self[config_key] = v |
<SYSTEM_TASK:>
Parse a parameter string into its constituent name, type, and
<END_TASK>
<USER_TASK:>
Description:
def parse_parameter_string(cls, parameter_string):
"""Parse a parameter string into its constituent name, type, and
pattern
For example::
parse_parameter_string('<param_one:[A-z]>')` ->
('param_one', str, '[A-z]')
:param parameter_string: String to parse
:return: tuple containing
(parameter_name, parameter_type, parameter_pattern)
""" |
# We could receive NAME or NAME:PATTERN
name = parameter_string
pattern = "string"
if ":" in parameter_string:
name, pattern = parameter_string.split(":", 1)
if not name:
raise ValueError(
"Invalid parameter syntax: {}".format(parameter_string)
)
default = (str, pattern)
# Pull from pre-configured types
_type, pattern = REGEX_TYPES.get(pattern, default)
return name, _type, pattern |
<SYSTEM_TASK:>
Check if a URL pattern exists in a list of routes provided based on
<END_TASK>
<USER_TASK:>
Description:
def check_dynamic_route_exists(pattern, routes_to_check, parameters):
"""
Check if a URL pattern exists in a list of routes provided based on
the comparison of URL pattern and the parameters.
:param pattern: URL parameter pattern
:param routes_to_check: list of dynamic routes either hashable or
unhashable routes.
:param parameters: List of :class:`Parameter` items
:return: Tuple of index and route if matching route exists else
-1 for index and None for route
""" |
for ndx, route in enumerate(routes_to_check):
if route.pattern == pattern and route.parameters == parameters:
return ndx, route
else:
return -1, None |
<SYSTEM_TASK:>
Get a request handler based on the URL of the request, or raises an
<END_TASK>
<USER_TASK:>
Description:
def get(self, request):
"""Get a request handler based on the URL of the request, or raises an
error
:param request: Request object
:return: handler, arguments, keyword arguments
""" |
# No virtual hosts specified; default behavior
if not self.hosts:
return self._get(request.path, request.method, "")
# virtual hosts specified; try to match route to the host header
try:
return self._get(
request.path, request.method, request.headers.get("Host", "")
)
# try default hosts
except NotFound:
return self._get(request.path, request.method, "") |
<SYSTEM_TASK:>
Get a list of supported methods for a url and optional host.
<END_TASK>
<USER_TASK:>
Description:
def get_supported_methods(self, url):
"""Get a list of supported methods for a url and optional host.
:param url: URL string (including host)
:return: frozenset of supported methods
""" |
route = self.routes_all.get(url)
# if methods are None then this logic will prevent an error
return getattr(route, "methods", None) or frozenset() |
<SYSTEM_TASK:>
Create a new process and a subprocess in it with the same arguments as
<END_TASK>
<USER_TASK:>
Description:
def restart_with_reloader():
"""Create a new process and a subprocess in it with the same arguments as
this one.
""" |
cwd = os.getcwd()
args = _get_args_for_reloading()
new_environ = os.environ.copy()
new_environ["SANIC_SERVER_RUNNING"] = "true"
cmd = " ".join(args)
worker_process = Process(
target=subprocess.call,
args=(cmd,),
kwargs={"cwd": cwd, "shell": True, "env": new_environ},
)
worker_process.start()
return worker_process |
<SYSTEM_TASK:>
Find and kill child processes of a process.
<END_TASK>
<USER_TASK:>
Description:
def kill_process_children(pid):
"""Find and kill child processes of a process.
:param pid: PID of parent process (process ID)
:return: Nothing
""" |
if sys.platform == "darwin":
kill_process_children_osx(pid)
elif sys.platform == "linux":
kill_process_children_unix(pid)
else:
pass |
<SYSTEM_TASK:>
Watch project files, restart worker process if a change happened.
<END_TASK>
<USER_TASK:>
Description:
def watchdog(sleep_interval):
"""Watch project files, restart worker process if a change happened.
:param sleep_interval: interval in second.
:return: Nothing
""" |
mtimes = {}
worker_process = restart_with_reloader()
signal.signal(
signal.SIGTERM, lambda *args: kill_program_completly(worker_process)
)
signal.signal(
signal.SIGINT, lambda *args: kill_program_completly(worker_process)
)
while True:
for filename in _iter_module_files():
try:
mtime = os.stat(filename).st_mtime
except OSError:
continue
old_time = mtimes.get(filename)
if old_time is None:
mtimes[filename] = mtime
continue
elif mtime > old_time:
kill_process_children(worker_process.pid)
worker_process.terminate()
worker_process = restart_with_reloader()
mtimes[filename] = mtime
break
sleep(sleep_interval) |
<SYSTEM_TASK:>
Return view function for use with the routing system, that
<END_TASK>
<USER_TASK:>
Description:
def as_view(cls, *class_args, **class_kwargs):
"""Return view function for use with the routing system, that
dispatches request to appropriate handler method.
""" |
def view(*args, **kwargs):
self = view.view_class(*class_args, **class_kwargs)
return self.dispatch_request(*args, **kwargs)
if cls.decorators:
view.__module__ = cls.__module__
for decorator in cls.decorators:
view = decorator(view)
view.view_class = cls
view.__doc__ = cls.__doc__
view.__module__ = cls.__module__
view.__name__ = cls.__name__
return view |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.