Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function: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, sel...
[ "|coro|\n\n Deletes the message.\n\n Your own messages could be deleted without any proper permissions. However to\n delete other people's messages, you need the :attr:`~Permissions.manage_messages`\n permission.\n\n .. versionchanged:: 1.1.0\n Added the new ``delay`` k...
Please provide a description of the function:async def edit(self, **fields): try: content = fields['content'] except KeyError: pass else: if content is not None: fields['content'] = str(content) try: embed = field...
[ "|coro|\n\n Edits the message.\n\n The content must be able to be transformed into a string via ``str(content)``.\n\n Parameters\n -----------\n content: Optional[:class:`str`]\n The new content to replace the message with.\n Could be ``None`` to remove the c...
Please provide a description of the function:async def pin(self): await self._state.http.pin_message(self.channel.id, self.id) self.pinned = True
[ "|coro|\n\n Pins the message.\n\n You must have the :attr:`~Permissions.manage_messages` permission to do\n this in a non-private channel context.\n\n Raises\n -------\n Forbidden\n You do not have permissions to pin the message.\n NotFound\n Th...
Please provide a description of the function:async def unpin(self): await self._state.http.unpin_message(self.channel.id, self.id) self.pinned = False
[ "|coro|\n\n Unpins the message.\n\n You must have the :attr:`~Permissions.manage_messages` permission to do\n this in a non-private channel context.\n\n Raises\n -------\n Forbidden\n You do not have permissions to unpin the message.\n NotFound\n ...
Please provide a description of the function:async def add_reaction(self, emoji): emoji = self._emoji_reaction(emoji) await self._state.http.add_reaction(self.channel.id, self.id, emoji)
[ "|coro|\n\n Add a reaction to the message.\n\n The emoji may be a unicode emoji or a custom guild :class:`Emoji`.\n\n You must have the :attr:`~Permissions.read_message_history` permission\n to use this. If nobody else has reacted to the message using this\n emoji, the :attr:`~Per...
Please provide a description of the function: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._s...
[ "|coro|\n\n Remove a reaction by the member from the message.\n\n The emoji may be a unicode emoji or a custom guild :class:`Emoji`.\n\n If the reaction is not your own (i.e. ``member`` parameter is not you) then\n the :attr:`~Permissions.manage_messages` permission is needed.\n\n ...
Please provide a description of the function:async def clear_reactions(self): await self._state.http.clear_reactions(self.channel.id, self.id)
[ "|coro|\n\n Removes all the reactions from the message.\n\n You need the :attr:`~Permissions.manage_messages` permission to use this.\n\n Raises\n --------\n HTTPException\n Removing the reactions failed.\n Forbidden\n You do not have the proper permis...
Please provide a description of the function: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|\n\n Marks this message as read.\n\n The user must not be a bot user.\n\n Raises\n -------\n HTTPException\n Acking failed.\n ClientException\n You must not be a bot user.\n " ]
Please provide a description of the function: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.co...
[ "Optional[:class:`str`]: Returns a URL pointing to the large image asset of this activity if applicable." ]
Please provide a description of the function: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.co...
[ "Optional[:class:`str`]: Returns a URL pointing to the small image asset of this activity if applicable." ]
Please provide a description of the function: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." ]
Please provide a description of the function: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.\n\n These are meant to be passed into the :attr:`.Bot.command_prefix` attribute.\n\n Example\n --------\n\n .. code-block:: python3\n\n bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))\n\n\n .. note::\n\n ...
Please provide a description of the function: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._g...
[ "|coro|\n\n The default command error handler provided by the bot.\n\n By default this prints to ``sys.stderr`` however it could be\n overridden to have a different implementation.\n\n This only fires if you do not specify any listeners for command error.\n " ]
Please provide a description of the function: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.\n\n This is the non-decorator interface to :meth:`.check`\n and :meth:`.check_once`.\n\n Parameters\n -----------\n func\n The function that was used as a global check.\n call_once: :class:`bool`\n If the function shoul...
Please provide a description of the function: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.\n\n This function is idempotent and will not raise an exception\n if the function is not in the global checks.\n\n Parameters\n -----------\n func\n The function to remove from the global checks.\n call_once: :class:`bool`\n ...
Please provide a description of the function: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\n this bot.\n\n If an :attr:`owner_id` is not set, it is fetched automatically\n through the use of :meth:`~.Bot.application_info`.\n\n Parameters\n -----------\n user: :class:`.abc.User`\n ...
Please provide a description of the function: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.ext...
[ "The non decorator alternative to :meth:`.listen`.\n\n Parameters\n -----------\n func: :ref:`coroutine <coroutine>`\n The function to call.\n name: Optional[:class:`str`]\n The name of the event to listen for. Defaults to ``func.__name__``.\n\n Example\n ...
Please provide a description of the function: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.\n\n Parameters\n -----------\n func\n The function that was used as a listener to remove.\n name: :class:`str`\n The name of the event we want to remove. Defaults to\n ``func.__name__``.\n " ]
Please provide a description of the function: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\n event listener. Basically this allows you to listen to multiple\n events from different places e.g. such as :func:`.on_ready`\n\n The functions being listened to must be a coroutine.\n\n Example\n --------\n\n .....
Please provide a description of the function: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.\n\n A cog is a class that has its own event listeners and commands.\n\n Parameters\n -----------\n cog: :class:`.Cog`\n The cog to register to the bot.\n\n Raises\n -------\n TypeError\n The cog does not inherit from ...
Please provide a description of the function: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(s...
[ "Removes a cog from the bot.\n\n All registered commands and event listeners that the\n cog has registered will be removed as well.\n\n If no cog is found then this method has no effect.\n\n Parameters\n -----------\n name: :class:`str`\n The name of the cog to r...
Please provide a description of the function: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(nam...
[ "Loads an extension.\n\n An extension is a python module that contains commands, cogs, or\n listeners.\n\n An extension must have a global function, ``setup`` defined as\n the entry point on what to do when the extension is loaded. This entry\n point must have a single argument, t...
Please provide a description of the function: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.\n\n When the extension is unloaded, all commands, listeners, and cogs are\n removed from the bot and the module is un-imported.\n\n The extension can provide an optional global function, ``teardown``,\n to do miscellaneous clean-up if necessary. This function takes...
Please provide a description of the function: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 ...
[ "Atomically reloads an extension.\n\n This replaces the extension with the same extension, only refreshed. This is\n equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension`\n except done in an atomic way. That is, if an operation fails mid-reload then\n the bot will...
Please provide a description of the function: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 = lis...
[ "|coro|\n\n Retrieves the prefix the bot is listening to\n with the message as a context.\n\n Parameters\n -----------\n message: :class:`discord.Message`\n The message context to get the prefix of.\n\n Returns\n --------\n Union[List[:class:`str`],...
Please provide a description of the function:async def get_context(self, message, *, cls=Context): r 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 pre...
[ "|coro|\n\n Returns the invocation context from the message.\n\n This is a more low-level counter-part for :meth:`.process_commands`\n to allow users more fine grained control over the processing.\n\n The returned context is not guaranteed to be a valid invocation\n context, :attr...
Please provide a description of the function: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.Comman...
[ "|coro|\n\n Invokes the command given under the invocation context and\n handles all the internal event dispatch mechanisms.\n\n Parameters\n -----------\n ctx: :class:`.Context`\n The invocation context to invoke.\n " ]
Please provide a description of the function:async def process_commands(self, message): if message.author.bot: return ctx = await self.get_context(message) await self.invoke(ctx)
[ "|coro|\n\n This function processes the commands that have been registered\n to the bot and other groups. Without this coroutine, none of the\n commands will be triggered.\n\n By default, this coroutine is called inside the :func:`.on_message`\n event. If you choose to override th...
Please provide a description of the function: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.\n\n A large guild is defined as having more than ``large_threshold`` count\n members, which for this library is set to the maximum of 250.\n " ]
Please provide a description of the function: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.\n\n This is sorted by the position and are in UI order from top to bottom.\n " ]
Please provide a description of the function: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`.\n This is essentially used to get the member version of yourself.\n " ]
Please provide a description of the function: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.\n\n This is sorted by the position and are in UI order from top to bottom.\n " ]
Please provide a description of the function: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.\n\n This is sorted by the position and are in UI order from top to bottom.\n " ]
Please provide a description of the function: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): ...
[ "Returns every :class:`CategoryChannel` and their associated channels.\n\n These channels and categories are sorted in the official Discord UI order.\n\n If the channels do not have a category, then the first element of the tuple is\n ``None``.\n\n Returns\n --------\n List...
Please provide a description of the function: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.\n\n Currently this is only for new member joins. If no channel is set, then this returns ``None``.\n " ]
Please provide a description of the function: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." ]
Please provide a description of the function: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\".\n\n A chunked guild means that :attr:`member_count` is equal to the\n number of members stored in the internal :attr:`members` cache.\n\n If this value returns ``False``, then you should request for\n offline members.\n " ...
Please provide a description of the function: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." ]
Please provide a description of the function: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 ...
[ "Returns the first member found that matches the name provided.\n\n The name can have an optional discriminator argument, e.g. \"Jake#0001\"\n or \"Jake\" will both do the lookup. However the former will give a more\n precise result. Note that the discriminator must have all 4 digits\n f...
Please provide a description of the function: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, g...
[ "|coro|\n\n Creates a :class:`TextChannel` for the guild.\n\n Note that you need the :attr:`~Permissions.manage_channels` permission\n to create the channel.\n\n The ``overwrites`` parameter can be used to create a 'secret'\n channel upon creation. This parameter expects a :class:...
Please provide a description of the function: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...
[ "|coro|\n\n This is similar to :meth:`create_text_channel` except makes a :class:`VoiceChannel` instead, in addition\n to having the following new parameters.\n\n Parameters\n -----------\n bitrate: :class:`int`\n The channel's preferred audio bitrate in bits per second...
Please provide a description of the function: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) # temporaril...
[ "|coro|\n\n Same as :meth:`create_text_channel` except makes a :class:`CategoryChannel` instead.\n\n .. note::\n\n The ``category`` parameter is not supported in this function since categories\n cannot have categories.\n " ]
Please provide a description of the function: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 = ut...
[ "|coro|\n\n Edits the guild.\n\n You must have the :attr:`~Permissions.manage_guild` permission\n to edit the guild.\n\n Parameters\n ----------\n name: :class:`str`\n The new name of the guild.\n description: :class:`str`\n The new description ...
Please provide a description of the function: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|\n\n Retreives a :class:`Member` from a guild ID, and a member ID.\n\n .. note::\n\n This method is an API call. For general usage, consider :meth:`get_member` instead.\n\n Parameters\n -----------\n member_id: :class:`int`\n The member's ID to fetch f...
Please provide a description of the function: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|\n\n Retrieves the :class:`BanEntry` for a user, which is a namedtuple\n with a ``user`` and ``reason`` field. See :meth:`bans` for more\n information.\n\n You must have the :attr:`~Permissions.ban_members` permission\n to get this information.\n\n Parameters\n ...
Please provide a description of the function: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|\n\n Retrieves all the users that are banned from the guild.\n\n This coroutine returns a :class:`list` of BanEntry objects, which is a\n namedtuple with a ``user`` field to denote the :class:`User`\n that got banned along with a ``reason`` field specifying\n why the user w...
Please provide a description of the function:async def prune_members(self, *, days, compute_prune_count=True, reason=None): r if not isinstance(days, int): raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days)) data = await self._s...
[ "|coro|\n\n Prunes the guild from its inactive members.\n\n The inactive members are denoted if they have not logged on in\n ``days`` number of days and they have no roles.\n\n You must have the :attr:`~Permissions.kick_members` permission\n to use this.\n\n To check how ma...
Please provide a description of the function: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_memb...
[ "|coro|\n\n Similar to :meth:`prune_members` except instead of actually\n pruning members, it returns how many members it would prune\n from the guild had it been called.\n\n Parameters\n -----------\n days: :class:`int`\n The number of days before counting as in...
Please provide a description of the function: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['gui...
[ "|coro|\n\n Returns a list of all active instant invites from the guild.\n\n You must have the :attr:`~Permissions.manage_guild` permission to get\n this information.\n\n Raises\n -------\n Forbidden\n You do not have proper permissions to get the information.\n ...
Please provide a description of the function:async def fetch_emojis(self): r data = await self._state.http.get_all_custom_emojis(self.id) return [Emoji(guild=self, state=self._state, data=d) for d in data]
[ "|coro|\n\n Retrieves all custom :class:`Emoji`\\s from the guild.\n\n .. note::\n\n This method is an API call. For general usage, consider :attr:`emojis` instead.\n\n Raises\n ---------\n HTTPException\n An error occurred fetching the emojis.\n\n Ret...
Please provide a description of the function: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|\n\n Retrieves a custom :class:`Emoji` from the guild.\n\n .. note::\n\n This method is an API call.\n For general usage, consider iterating over :attr:`emojis` instead.\n\n Parameters\n -------------\n emoji_id: :class:`int`\n The emoji's I...
Please provide a description of the function:async def create_custom_emoji(self, *, name, image, roles=None, reason=None): r 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...
[ "|coro|\n\n Creates a custom :class:`Emoji` for the guild.\n\n There is currently a limit of 50 static and animated emojis respectively per guild,\n unless the guild has the ``MORE_EMOJI`` feature which extends the limit to 200.\n\n You must have the :attr:`~Permissions.manage_emojis` pe...
Please provide a description of the function:async def create_role(self, *, reason=None, **fields): try: perms = fields.pop('permissions') except KeyError: fields['permissions'] = 0 else: fields['permissions'] = perms.value try: ...
[ "|coro|\n\n Creates a :class:`Role` for the guild.\n\n All fields are optional.\n\n You must have the :attr:`~Permissions.manage_roles` permission to\n do this.\n\n Parameters\n -----------\n name: :class:`str`\n The role name. Defaults to 'new role'.\n ...
Please provide a description of the function:async def kick(self, user, *, reason=None): await self._state.http.kick(user.id, self.id, reason=reason)
[ "|coro|\n\n Kicks a user from the guild.\n\n The user must meet the :class:`abc.Snowflake` abc.\n\n You must have the :attr:`~Permissions.kick_members` permission to\n do this.\n\n Parameters\n -----------\n user: :class:`abc.Snowflake`\n The user to kick ...
Please provide a description of the function: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|\n\n Bans a user from the guild.\n\n The user must meet the :class:`abc.Snowflake` abc.\n\n You must have the :attr:`~Permissions.ban_members` permission to\n do this.\n\n Parameters\n -----------\n user: :class:`abc.Snowflake`\n The user to ban fro...
Please provide a description of the function:async def unban(self, user, *, reason=None): await self._state.http.unban(user.id, self.id, reason=reason)
[ "|coro|\n\n Unbans a user from the guild.\n\n The user must meet the :class:`abc.Snowflake` abc.\n\n You must have the :attr:`~Permissions.ban_members` permission to\n do this.\n\n Parameters\n -----------\n user: :class:`abc.Snowflake`\n The user to unban...
Please provide a description of the function: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 sel...
[ "|coro|\n\n Returns the guild's special vanity invite.\n\n The guild must be partnered, i.e. have 'VANITY_URL' in\n :attr:`~Guild.features`.\n\n You must have the :attr:`~Permissions.manage_guild` permission to use\n this as well.\n\n Raises\n -------\n Forbid...
Please provide a description of the function: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|\n\n Marks every message in this guild as read.\n\n The user must not be a bot user.\n\n Raises\n -------\n HTTPException\n Acking failed.\n ClientException\n You must not be a bot user.\n " ]
Please provide a description of the function: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=afte...
[ "Return an :class:`AsyncIterator` that enables receiving the guild's audit logs.\n\n You must have the :attr:`~Permissions.view_audit_log` permission to use this.\n\n Examples\n ----------\n\n Getting the first 100 entries: ::\n\n async for entry in guild.audit_logs(limit=100)...
Please provide a description of the function:async def widget(self): data = await self._state.http.get_widget(self.id) return Widget(state=self._state, data=data)
[ "|coro|\n\n Returns the widget of the guild.\n\n .. note::\n\n The guild must have the widget enabled to get this information.\n\n Raises\n -------\n Forbidden\n The widget for this guild is disabled.\n HTTPException\n Retrieving the widget ...
Please provide a description of the function:def latency(self): if not self.shards: return float('nan') return sum(latency for _, latency in self.latencies) / len(self.shards)
[ ":class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.\n\n This operates similarly to :meth:`.Client.latency` except it uses the average\n latency of every shard's latency. To get a list of shard latency, check the\n :attr:`latencies` property. Returns ``nan`` if ...
Please provide a description of the function:def latencies(self): return [(shard_id, shard.ws.latency) for shard_id, shard in self.shards.items()]
[ "List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds.\n\n This returns a list of tuples with elements ``(shard_id, latency)``.\n " ]
Please provide a description of the function:async def request_offline_members(self, *guilds): r if any(not g.large or g.unavailable for g in guilds): raise InvalidArgument('An unavailable or non-large guild was passed.') _guilds = sorted(guilds, key=lambda g: g.shard_id) fo...
[ "|coro|\n\n Requests previously offline members from the guild to be filled up\n into the :attr:`Guild.members` cache. This function is usually not\n called. It should only be used if you have the ``fetch_offline_members``\n parameter set to ``False``.\n\n When the client logs on ...
Please provide a description of the function:async def close(self): if self.is_closed(): return self._closed = True for vc in self.voice_clients: try: await vc.disconnect() except Exception: pass to_close = [...
[ "|coro|\n\n Closes the connection to discord.\n " ]
Please provide a description of the function:async def change_presence(self, *, activity=None, status=None, afk=False, shard_id=None): if status is None: status = 'online' status_enum = Status.online elif status is Status.offline: status = 'invisible' ...
[ "|coro|\n\n Changes the client's presence.\n\n The activity parameter is a :class:`Activity` object (not a string) that represents\n the activity being done currently. This could also be the slimmed down versions,\n :class:`Game` and :class:`Streaming`.\n\n Example: ::\n\n ...
Please provide a description of the function:def members(self): all_members = self.guild.members if self.is_default(): return all_members role_id = self.id return [member for member in all_members if member._roles.has(role_id)]
[ "Returns a :class:`list` of :class:`Member` with this role." ]
Please provide a description of the function:async def edit(self, *, reason=None, **fields): position = fields.get('position') if position is not None: await self._move(position, reason=reason) self.position = position try: colour = fields['colour']...
[ "|coro|\n\n Edits the role.\n\n You must have the :attr:`~Permissions.manage_roles` permission to\n use this.\n\n All fields are optional.\n\n Parameters\n -----------\n name: :class:`str`\n The new role name to change to.\n permissions: :class:`Per...
Please provide a description of the function:async def delete(self, *, reason=None): await self._state.http.delete_role(self.guild.id, self.id, reason=reason)
[ "|coro|\n\n Deletes the role.\n\n You must have the :attr:`~Permissions.manage_roles` permission to\n use this.\n\n Parameters\n -----------\n reason: Optional[:class:`str`]\n The reason for deleting this role. Shows up on the audit log.\n\n Raises\n ...
Please provide a description of the function:def group(*blueprints, url_prefix=""): def chain(nested): for i in nested: if isinstance(i, (list, tuple)): yield from chain(i) elif isinstance(i, BlueprintGroup): ...
[ "\n Create a list of blueprints, optionally grouping them under a\n general URL prefix.\n\n :param blueprints: blueprints to be registered as a group\n :param url_prefix: URL route to be prepended to all sub-prefixes\n ", "itertools.chain() but leaves strings untouched" ]
Please provide a description of the function:def register(self, app, options): 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 ro...
[ "\n Register the blueprint to the sanic app.\n\n :param app: Instance of :class:`sanic.app.Sanic` class\n :param options: Options to be used while registering the\n blueprint into the app.\n *url_prefix* - URL Prefix to override the blueprint prefix\n " ]
Please provide a description of the function:def route( self, uri, methods=frozenset({"GET"}), host=None, strict_slashes=None, stream=False, version=None, name=None, ): if strict_slashes is None: strict_slashes = self.stric...
[ "Create a blueprint route from a decorated function.\n\n :param uri: endpoint at which the route will be accessible.\n :param methods: list of acceptable HTTP methods.\n :param host: IP Address of FQDN for the sanic server to use.\n :param strict_slashes: Enforce the API urls are request...
Please provide a description of the function:def websocket( self, uri, host=None, strict_slashes=None, version=None, name=None ): if strict_slashes is None: strict_slashes = self.strict_slashes def decorator(handler): route = FutureRoute( han...
[ "Create a blueprint websocket route from a decorated function.\n\n :param uri: endpoint at which the route will be accessible.\n :param host: IP Address of FQDN for the sanic server to use.\n :param strict_slashes: Enforce the API urls are requested with a\n training */*\n :pa...
Please provide a description of the function:def add_websocket_route( self, handler, uri, host=None, version=None, name=None ): self.websocket(uri=uri, host=host, version=version, name=name)(handler) return handler
[ "Create a blueprint websocket route from a function.\n\n :param handler: function for handling uri requests. Accepts function,\n or class instance with a view_class method.\n :param uri: endpoint at which the route will be accessible.\n :param host: IP Address of FQDN for...
Please provide a description of the function:def listener(self, event): def decorator(listener): self.listeners[event].append(listener) return listener return decorator
[ "Create a listener from a decorated function.\n\n :param event: Event to listen to.\n " ]
Please provide a description of the function:def middleware(self, *args, **kwargs): def register_middleware(_middleware): future_middleware = FutureMiddleware(_middleware, args, kwargs) self.middlewares.append(future_middleware) return _middleware # Detect ...
[ "\n Create a blueprint middleware from a decorated function.\n\n :param args: Positional arguments to be used while invoking the\n middleware\n :param kwargs: optional keyword args that can be used with the\n middleware.\n " ]
Please provide a description of the function:def exception(self, *args, **kwargs): def decorator(handler): exception = FutureException(handler, args, kwargs) self.exceptions.append(exception) return handler return decorator
[ "\n This method enables the process of creating a global exception\n handler for the current blueprint under question.\n\n :param args: List of Python exceptions to be caught by the handler\n :param kwargs: Additional optional arguments to be passed to the\n exception handler\...
Please provide a description of the function:def static(self, uri, file_or_directory, *args, **kwargs): name = kwargs.pop("name", "static") if not name.startswith(self.name + "."): name = "{}.{}".format(self.name, name) kwargs.update(name=name) strict_slashes = kwar...
[ "Create a blueprint static route from a decorated function.\n\n :param uri: endpoint at which the route will be accessible.\n :param file_or_directory: Static asset.\n " ]
Please provide a description of the function:def get( self, uri, host=None, strict_slashes=None, version=None, name=None ): return self.route( uri, methods=frozenset({"GET"}), host=host, strict_slashes=strict_slashes, version=versi...
[ "\n Add an API URL under the **GET** *HTTP* method\n\n :param uri: URL to be tagged to **GET** method of *HTTP*\n :param host: Host IP or FQDN for the service to use\n :param strict_slashes: Instruct :class:`sanic.app.Sanic` to check\n if the request URLs need to terminate wit...
Please provide a description of the function:def add_status_code(code): def class_decorator(cls): cls.status_code = code _sanic_exceptions[code] = cls return cls return class_decorator
[ "\n Decorator used for adding exceptions to :class:`SanicException`.\n " ]
Please provide a description of the function:def abort(status_code, message=None): 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, S...
[ "\n Raise an exception based on SanicException. Returns the HTTP response\n message appropriate for the given status code, unless provided.\n\n :param status_code: The HTTP status code to return.\n :param message: The HTTP response body. Defaults to the messages\n in response.py for t...
Please provide a description of the function:def add_task(self, task): try: if callable(task): try: self.loop.create_task(task(self)) except TypeError: self.loop.create_task(task()) else: sel...
[ "Schedule a task to run later, after the loop has started.\n Different from asyncio.ensure_future in that it does not\n also return a future, and the actual ensure_future call\n is delayed until before server start.\n\n :param task: future, couroutine or awaitable\n " ]
Please provide a description of the function:def route( self, uri, methods=frozenset({"GET"}), host=None, strict_slashes=None, stream=False, version=None, name=None, ): # Fix case where the user did not prefix the URL with a / ...
[ "Decorate a function to be registered as a route\n\n :param uri: path of the URL\n :param methods: list or tuple of methods allowed\n :param host:\n :param strict_slashes:\n :param stream:\n :param version:\n :param name: user defined route name for url_for\n ...
Please provide a description of the function:def websocket( self, uri, host=None, strict_slashes=None, subprotocols=None, name=None ): self.enable_websocket() # Fix case where the user did not prefix the URL with a / # and will probably get confused as to why it's not worki...
[ "Decorate a function to be registered as a websocket route\n :param uri: path of the URL\n :param subprotocols: optional list of str with supported subprotocols\n :param host:\n :return: decorated function\n " ]
Please provide a description of the function:def add_websocket_route( self, handler, uri, host=None, strict_slashes=None, subprotocols=None, name=None, ): if strict_slashes is None: strict_slashes = self.strict_slashes ret...
[ "\n A helper method to register a function as a websocket route.\n\n :param handler: a callable function or instance of a class\n that can handle the websocket request\n :param host: Host IP or FQDN details\n :param uri: URL path that will be mapped to the websocke...
Please provide a description of the function:def enable_websocket(self, enable=True): 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")...
[ "Enable or disable the support for websocket.\n\n Websocket is enabled automatically if websocket routes are\n added to the application.\n " ]
Please provide a description of the function:def remove_route(self, uri, clean_cache=True, host=None): self.router.remove(uri, clean_cache, host)
[ "\n This method provides the app user a mechanism by which an already\n existing route can be removed from the :class:`Sanic` object\n\n :param uri: URL Path to be removed from the app\n :param clean_cache: Instruct sanic if it needs to clean up the LRU\n route cache\n ...
Please provide a description of the function:def exception(self, *exceptions): def response(handler): for exception in exceptions: if isinstance(exception, (tuple, list)): for e in exception: self.error_handler.add(e, handler) ...
[ "Decorate a function to be registered as a handler for exceptions\n\n :param exceptions: exceptions\n :return: decorated function\n " ]
Please provide a description of the function:def register_middleware(self, middleware, attach_to="request"): if attach_to == "request": if middleware not in self.request_middleware: self.request_middleware.append(middleware) if attach_to == "response": if...
[ "\n Register an application level middleware that will be attached\n to all the API URLs registered under this application.\n\n This method is internally invoked by the :func:`middleware`\n decorator provided at the app level.\n\n :param middleware: Callback method to be attached ...
Please provide a description of the function:def middleware(self, middleware_or_request): # Detect which way this was called, @middleware or @middleware('AT') if callable(middleware_or_request): return self.register_middleware(middleware_or_request) else: return...
[ "\n Decorate and register middleware to be called before a request.\n Can either be called as *@app.middleware* or\n *@app.middleware('request')*\n\n :param: middleware_or_request: Optional parameter to use for\n identifying which type of middleware is being registered.\n ...
Please provide a description of the function:def static( self, uri, file_or_directory, pattern=r"/?.+", use_modified_since=True, use_content_range=False, stream_large_files=False, name="static", host=None, strict_slashes=None, conte...
[ "\n Register a root to serve files from. The input can either be a\n file or a directory. This method will enable an easy and simple way\n to setup the :class:`Route` necessary to serve the static files.\n\n :param uri: URL path to be used for serving static content\n :param file_...
Please provide a description of the function:def blueprint(self, blueprint, **options): if isinstance(blueprint, (list, tuple, BlueprintGroup)): for item in blueprint: self.blueprint(item, **options) return if blueprint.name in self.blueprints: ...
[ "Register a blueprint on the application.\n\n :param blueprint: Blueprint object or (list, tuple) thereof\n :param options: option dictionary with blueprint defaults\n :return: Nothing\n " ]
Please provide a description of the function:def register_blueprint(self, *args, **kwargs): if self.debug: warnings.simplefilter("default") warnings.warn( "Use of register_blueprint will be deprecated in " "version 1.0. Please use the blueprint method" ...
[ "\n Proxy method provided for invoking the :func:`blueprint` method\n\n .. note::\n To be deprecated in 1.0. Use :func:`blueprint` instead.\n\n :param args: Blueprint object or (list, tuple) thereof\n :param kwargs: option dictionary with blueprint defaults\n :return: N...
Please provide a description of the function:async def handle_request(self, request, write_callback, stream_callback): # Define `response` var here to remove warnings about # allocation before assignment below. response = None cancelled = False try: # -------...
[ "Take a request from the HTTP Server and return a response object\n to be sent back The HTTP Server only expects a response object, so\n exception handling must be done here\n\n :param request: HTTP Request object\n :param write_callback: Synchronous response function to be\n ...
Please provide a description of the function: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] = ...
[ "Run the HTTP Server and listen until keyboard interrupt or term\n signal. On termination, drain connections before closing.\n\n :param host: Address to host on\n :type host: str\n :param port: Port to host on\n :type port: int\n :param debug: Enables debug output (slows se...
Please provide a description of the function:async def create_server( self, host: Optional[str] = None, port: Optional[int] = None, debug: bool = False, ssl: Union[dict, SSLContext, None] = None, sock: Optional[socket] = None, protocol: Type[Protocol] = None, ...
[ "\n Asynchronous version of :func:`run`.\n\n This method will take care of the operations necessary to invoke\n the *before_start* events via :func:`trigger_events` method invocation\n before starting the *sanic* app in Async mode.\n\n .. note::\n This does not support ...
Please provide a description of the function:def _helper( self, host=None, port=None, debug=False, ssl=None, sock=None, workers=1, loop=None, protocol=HttpProtocol, backlog=100, stop_event=None, register_sys_signals=True, ...
[ "Helper function used by `run` and `create_server`." ]
Please provide a description of the function:def json( body, status=200, headers=None, content_type="application/json", dumps=json_dumps, **kwargs ): return HTTPResponse( dumps(body, **kwargs), headers=headers, status=status, content_type=content_type, ...
[ "\n Returns response object with body in json format.\n\n :param body: Response data to be serialized.\n :param status: Response code.\n :param headers: Custom Headers.\n :param kwargs: Remaining arguments that are passed to the json encoder.\n " ]
Please provide a description of the function:def text( body, status=200, headers=None, content_type="text/plain; charset=utf-8" ): return HTTPResponse( body, status=status, headers=headers, content_type=content_type )
[ "\n Returns response object with body in text format.\n\n :param body: Response data to be encoded.\n :param status: Response code.\n :param headers: Custom Headers.\n :param content_type: the content type (string) of the response\n " ]
Please provide a description of the function:async def file_stream( location, status=200, chunk_size=4096, mime_type=None, headers=None, filename=None, _range=None, ): headers = headers or {} if filename: headers.setdefault( "Content-Disposition", 'attachment...
[ "Return a streaming response object with file data.\n\n :param location: Location of file on system.\n :param chunk_size: The size of each chunk in the stream (in bytes)\n :param mime_type: Specific mime_type.\n :param headers: Custom Headers.\n :param filename: Override filename.\n :param _range:...
Please provide a description of the function:def stream( streaming_fn, status=200, headers=None, content_type="text/plain; charset=utf-8", ): return StreamingHTTPResponse( streaming_fn, headers=headers, content_type=content_type, status=status )
[ "Accepts an coroutine `streaming_fn` which can be used to\n write chunks to a streaming response. Returns a `StreamingHTTPResponse`.\n\n Example usage::\n\n @app.route(\"/\")\n async def index(request):\n async def streaming_fn(response):\n await response.write('foo')\n...