Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def me(self): return self.guild.me if self.guild is not None else self.bot.user
[ "Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts." ]
Please provide a description of the function:async def send_help(self, *args): from .core import Group, Command bot = self.bot cmd = bot.help_command if cmd is None: return None cmd = cmd.copy() cmd.context = self if len(args) == 0: ...
[ "send_help(entity=<bot>)\n\n |coro|\n\n Shows the help command for the specified entity if given.\n The entity can be a command or a cog.\n\n If no entity is given, then it'll show help for the\n entire bot.\n\n If the entity is a string, then it looks up whether it's a\n ...
Please provide a description of the function:def delay(self): invocation = time.monotonic() interval = invocation - self._last_invocation self._last_invocation = invocation if interval > self._reset_time: self._exp = 0 self._exp = min(self._exp + 1, self._m...
[ "Compute the next delay\n\n Returns the next delay to wait according to the exponential\n backoff algorithm. This is a value between 0 and base * 2^exp\n where exponent starts off at 1 and is incremented at every\n invocation of this method up to a maximum of 10.\n\n If a period ...
Please provide a description of the function:def is_subset(self, other): if isinstance(other, Permissions): return (self.value & other.value) == self.value else: raise TypeError("cannot compare {} with {}".format(self.__class__.__name__, other.__class__.__name__))
[ "Returns True if self has the same or fewer permissions as other." ]
Please provide a description of the function:def update(self, **kwargs): r for key, value in kwargs.items(): try: is_property = isinstance(getattr(self.__class__, key), property) except AttributeError: continue if is_property: ...
[ "Bulk updates this permission object.\n\n Allows you to set multiple attributes by using keyword\n arguments. The names must be equivalent to the properties\n listed. Extraneous key/value pairs will be silently ignored.\n\n Parameters\n ------------\n \\*\\*kwargs\n ...
Please provide a description of the function:def changes(self): obj = AuditLogChanges(self, self._changes) del self._changes return obj
[ ":class:`AuditLogChanges`: The list of changes this entry has." ]
Please provide a description of the function:def command(name=None, cls=None, **attrs): if cls is None: cls = Command def decorator(func): if isinstance(func, Command): raise TypeError('Callback is already a command.') return cls(func, name=name, **attrs) return de...
[ "A decorator that transforms a function into a :class:`.Command`\n or if called with :func:`.group`, :class:`.Group`.\n\n By default the ``help`` attribute is received automatically from the\n docstring of the function and is cleaned up with the use of\n ``inspect.cleandoc``. If the docstring is ``bytes...
Please provide a description of the function:def group(name=None, **attrs): attrs.setdefault('cls', Group) return command(name=name, **attrs)
[ "A decorator that transforms a function into a :class:`.Group`.\n\n This is similar to the :func:`.command` decorator but the ``cls``\n parameter is set to :class:`Group` by default.\n\n .. versionchanged:: 1.1.0\n The ``cls`` parameter can now be passed.\n " ]
Please provide a description of the function:def check(predicate): r def decorator(func): if isinstance(func, Command): func.checks.append(predicate) else: if not hasattr(func, '__commands_checks__'): func.__commands_checks__ = [] func.__comm...
[ "A decorator that adds a check to the :class:`.Command` or its\n subclasses. These checks could be accessed via :attr:`.Command.checks`.\n\n These checks should be predicates that take in a single parameter taking\n a :class:`.Context`. If the check returns a ``False``\\-like value then\n during invocat...
Please provide a description of the function:def has_role(item): def predicate(ctx): if not isinstance(ctx.channel, discord.abc.GuildChannel): raise NoPrivateMessage() if isinstance(item, int): role = discord.utils.get(ctx.author.roles, id=item) else: ...
[ "A :func:`.check` that is added that checks if the member invoking the\n command has the role specified via the name or ID specified.\n\n If a string is specified, you must give the exact name of the role, including\n caps and spelling.\n\n If an integer is specified, you must give the exact snowflake I...
Please provide a description of the function:def has_any_role(*items): r def predicate(ctx): if not isinstance(ctx.channel, discord.abc.GuildChannel): raise NoPrivateMessage() getter = functools.partial(discord.utils.get, ctx.author.roles) if any(getter(id=item) is not None ...
[ "A :func:`.check` that is added that checks if the member invoking the\n command has **any** of the roles specified. This means that if they have\n one out of the three roles specified, then this check will return `True`.\n\n Similar to :func:`.has_role`\\, the names or IDs passed in must be exact.\n\n ...
Please provide a description of the function:def bot_has_role(item): def predicate(ctx): ch = ctx.channel if not isinstance(ch, discord.abc.GuildChannel): raise NoPrivateMessage() me = ch.guild.me if isinstance(item, int): role = discord.utils.get(me.ro...
[ "Similar to :func:`.has_role` except checks if the bot itself has the\n role.\n\n This check raises one of two special exceptions, :exc:`.BotMissingRole` if the bot\n is missing the role, or :exc:`.NoPrivateMessage` if it is used in a private message.\n Both inherit from :exc:`.CheckFailure`.\n\n .. ...
Please provide a description of the function:def bot_has_any_role(*items): def predicate(ctx): ch = ctx.channel if not isinstance(ch, discord.abc.GuildChannel): raise NoPrivateMessage() me = ch.guild.me getter = functools.partial(discord.utils.get, me.roles) ...
[ "Similar to :func:`.has_any_role` except checks if the bot itself has\n any of the roles listed.\n\n This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot\n is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message.\n Both inherit from :exc:`.Ch...
Please provide a description of the function:def has_permissions(**perms): def predicate(ctx): ch = ctx.channel permissions = ch.permissions_for(ctx.author) missing = [perm for perm, value in perms.items() if getattr(permissions, perm, None) != value] if not missing: ...
[ "A :func:`.check` that is added that checks if the member has all of\n the permissions necessary.\n\n The permissions passed in must be exactly like the properties shown under\n :class:`.discord.Permissions`.\n\n This check raises a special exception, :exc:`.MissingPermissions`\n that is inherited fr...
Please provide a description of the function:def bot_has_permissions(**perms): def predicate(ctx): guild = ctx.guild me = guild.me if guild is not None else ctx.bot.user permissions = ctx.channel.permissions_for(me) missing = [perm for perm, value in perms.items() if getattr(pe...
[ "Similar to :func:`.has_permissions` except checks if the bot itself has\n the permissions listed.\n\n This check raises a special exception, :exc:`.BotMissingPermissions`\n that is inherited from :exc:`.CheckFailure`.\n " ]
Please provide a description of the function:def is_owner(): async def predicate(ctx): if not await ctx.bot.is_owner(ctx.author): raise NotOwner('You do not own this bot.') return True return check(predicate)
[ "A :func:`.check` that checks if the person invoking this command is the\n owner of the bot.\n\n This is powered by :meth:`.Bot.is_owner`.\n\n This check raises a special exception, :exc:`.NotOwner` that is derived\n from :exc:`.CheckFailure`.\n " ]
Please provide a description of the function:def is_nsfw(): def pred(ctx): ch = ctx.channel if ctx.guild is None or (isinstance(ch, discord.TextChannel) and ch.is_nsfw()): return True raise NSFWChannelRequired(ch) return check(pred)
[ "A :func:`.check` that checks if the channel is a NSFW channel.\n\n This check raises a special exception, :exc:`.NSFWChannelRequired`\n that is derived from :exc:`.CheckFailure`.\n\n .. versionchanged:: 1.1.0\n\n Raise :exc:`.NSFWChannelRequired instead of generic :exc:`.CheckFailure`.\n DM ...
Please provide a description of the function:def cooldown(rate, per, type=BucketType.default): def decorator(func): if isinstance(func, Command): func._buckets = CooldownMapping(Cooldown(rate, per, type)) else: func.__commands_cooldown__ = Cooldown(rate, per, type) ...
[ "A decorator that adds a cooldown to a :class:`.Command`\n or its subclasses.\n\n A cooldown allows a command to only be used a specific amount\n of times in a specific time frame. These cooldowns can be based\n either on a per-guild, per-channel, per-user, or global basis.\n Denoted by the third arg...
Please provide a description of the function:def update(self, **kwargs): self.__init__(self.callback, **dict(self.__original_kwargs__, **kwargs))
[ "Updates :class:`Command` instance with updated attribute.\n\n This works similarly to the :func:`.command` decorator in terms\n of parameters in that they are passed to the :class:`Command` or\n subclass constructors, sans the name and callback.\n " ]
Please provide a description of the function:def copy(self): ret = self.__class__(self.callback, **self.__original_kwargs__) return self._ensure_assignment_on_copy(ret)
[ "Creates a copy of this :class:`Command`." ]
Please provide a description of the function:def clean_params(self): result = self.params.copy() if self.cog is not None: # first parameter is self result.popitem(last=False) try: # first/second parameter is context result.popitem(last=Fa...
[ "Retrieves the parameter OrderedDict without the context or self parameters.\n\n Useful for inspecting signature.\n " ]
Please provide a description of the function:def full_parent_name(self): entries = [] command = self while command.parent is not None: command = command.parent entries.append(command.name) return ' '.join(reversed(entries))
[ "Retrieves the fully qualified parent command name.\n\n This the base command name required to execute it. For example,\n in ``?one two three`` the parent name would be ``one two``.\n " ]
Please provide a description of the function:def parents(self): entries = [] command = self while command.parent is not None: command = command.parent entries.append(command) return entries
[ "Retrieves the parents of this command.\n\n If the command has no parents then it returns an empty :class:`list`.\n\n For example in commands ``?a b c test``, the parents are ``[c, b, a]``.\n\n .. versionadded:: 1.1.0\n " ]
Please provide a description of the function:def qualified_name(self): parent = self.full_parent_name if parent: return parent + ' ' + self.name else: return self.name
[ "Retrieves the fully qualified command name.\n\n This is the full parent name with the command name as well.\n For example, in ``?one two three`` the qualified name would be\n ``one two three``.\n " ]
Please provide a description of the function:def is_on_cooldown(self, ctx): if not self._buckets.valid: return False bucket = self._buckets.get_bucket(ctx.message) return bucket.get_tokens() == 0
[ "Checks whether the command is currently on cooldown.\n\n Parameters\n -----------\n ctx: :class:`.Context.`\n The invocation context to use when checking the commands cooldown status.\n\n Returns\n --------\n :class:`bool`\n A boolean indicating if th...
Please provide a description of the function:def reset_cooldown(self, ctx): if self._buckets.valid: bucket = self._buckets.get_bucket(ctx.message) bucket.reset()
[ "Resets the cooldown on this command.\n\n Parameters\n -----------\n ctx: :class:`.Context`\n The invocation context to reset the cooldown under.\n " ]
Please provide a description of the function:def error(self, coro): if not asyncio.iscoroutinefunction(coro): raise TypeError('The error handler must be a coroutine.') self.on_error = coro return coro
[ "A decorator that registers a coroutine as a local error handler.\n\n A local error handler is an :func:`.on_command_error` event limited to\n a single command. However, the :func:`.on_command_error` is still\n invoked afterwards as the catch-all.\n\n Parameters\n -----------\n ...
Please provide a description of the function:def before_invoke(self, coro): if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke = coro return coro
[ "A decorator that registers a coroutine as a pre-invoke hook.\n\n A pre-invoke hook is called directly before the command is\n called. This makes it a useful function to set up database\n connections or any type of set up required.\n\n This pre-invoke hook takes a sole parameter, a :clas...
Please provide a description of the function:def after_invoke(self, coro): if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must be a coroutine.') self._after_invoke = coro return coro
[ "A decorator that registers a coroutine as a post-invoke hook.\n\n A post-invoke hook is called directly after the command is\n called. This makes it a useful function to clean-up database\n connections or any type of clean up required.\n\n This post-invoke hook takes a sole parameter, a...
Please provide a description of the function:def short_doc(self): if self.brief is not None: return self.brief if self.help is not None: return self.help.split('\n', 1)[0] return ''
[ "Gets the \"short\" documentation of a command.\n\n By default, this is the :attr:`brief` attribute.\n If that lookup leads to an empty string then the first line of the\n :attr:`help` attribute is used instead.\n " ]
Please provide a description of the function:def signature(self): if self.usage is not None: return self.usage params = self.clean_params if not params: return '' result = [] for name, param in params.items(): greedy = isinstance(pa...
[ "Returns a POSIX-like signature useful for help command output." ]
Please provide a description of the function:async def can_run(self, ctx): original = ctx.command ctx.command = self try: if not await ctx.bot.can_run(ctx): raise CheckFailure('The global check functions for command {0.qualified_name} failed.'.format(self))...
[ "|coro|\n\n Checks if the command can be executed by checking all the predicates\n inside the :attr:`.checks` attribute.\n\n Parameters\n -----------\n ctx: :class:`.Context`\n The ctx of the command currently being invoked.\n\n Raises\n -------\n :...
Please provide a description of the function:def add_command(self, command): if not isinstance(command, Command): raise TypeError('The command passed must be a subclass of Command') if isinstance(self, Command): command.parent = self if command.name in self.al...
[ "Adds a :class:`.Command` or its subclasses into the internal list\n of commands.\n\n This is usually not called, instead the :meth:`~.GroupMixin.command` or\n :meth:`~.GroupMixin.group` shortcut decorators are used instead.\n\n Parameters\n -----------\n command\n ...
Please provide a description of the function:def remove_command(self, name): command = self.all_commands.pop(name, None) # does not exist if command is None: return None if name in command.aliases: # we're removing an alias so we don't want to remove th...
[ "Remove a :class:`.Command` or subclasses from the internal list\n of commands.\n\n This could also be used as a way to remove aliases.\n\n Parameters\n -----------\n name: :class:`str`\n The name of the command to remove.\n\n Returns\n --------\n :...
Please provide a description of the function:def walk_commands(self): for command in tuple(self.all_commands.values()): yield command if isinstance(command, GroupMixin): yield from command.walk_commands()
[ "An iterator that recursively walks through all commands and subcommands." ]
Please provide a description of the function:def get_command(self, name): # fast path, no space in name. if ' ' not in name: return self.all_commands.get(name) names = name.split() obj = self.all_commands.get(names[0]) if not isinstance(obj, GroupMixin): ...
[ "Get a :class:`.Command` or subclasses from the internal list\n of commands.\n\n This could also be used as a way to get aliases.\n\n The name could be fully qualified (e.g. ``'foo bar'``) will get\n the subcommand ``bar`` of the group command ``foo``. If a\n subcommand is not fou...
Please provide a description of the function:def command(self, *args, **kwargs): def decorator(func): kwargs.setdefault('parent', self) result = command(*args, **kwargs)(func) self.add_command(result) return result return decorator
[ "A shortcut decorator that invokes :func:`.command` and adds it to\n the internal command list via :meth:`~.GroupMixin.add_command`.\n " ]
Please provide a description of the function:def copy(self): ret = super().copy() for cmd in self.commands: ret.add_command(cmd.copy()) return ret
[ "Creates a copy of this :class:`Group`." ]
Please provide a description of the function:async def read(self): if not self._url: raise DiscordException('Invalid asset (no URL provided)') if self._state is None: raise DiscordException('Invalid state (no ConnectionState provided)') return await self._state...
[ "|coro|\n\n Retrieves the content of this asset as a :class:`bytes` object.\n\n .. warning::\n\n :class:`PartialEmoji` won't have a connection state if user created,\n and a URL won't be present if a custom image isn't associated with\n the asset, e.g. a guild with no ...
Please provide a description of the function:async def save(self, fp, *, seek_begin=True): data = await self.read() if isinstance(fp, io.IOBase) and fp.writable(): written = fp.write(data) if seek_begin: fp.seek(0) return written else...
[ "|coro|\n\n Saves this asset into a file-like object.\n\n Parameters\n ----------\n fp: Union[BinaryIO, :class:`os.PathLike`]\n Same as in :meth:`Attachment.save`.\n seek_begin: :class:`bool`\n Same as in :meth:`Attachment.save`.\n\n Raises\n --...
Please provide a description of the function:async def from_client(cls, client, *, shard_id=None, session=None, sequence=None, resume=False): gateway = await client.http.get_gateway() ws = await websockets.connect(gateway, loop=client.loop, klass=cls, compression=None) # dynamically ad...
[ "Creates a main websocket for Discord from a :class:`Client`.\n\n This is for internal use only.\n " ]
Please provide a description of the function:def wait_for(self, event, predicate, result=None): future = self.loop.create_future() entry = EventListener(event=event, predicate=predicate, result=result, future=future) self._dispatch_listeners.append(entry) return future
[ "Waits for a DISPATCH'd event that meets the predicate.\n\n Parameters\n -----------\n event: :class:`str`\n The event name in all upper case to wait for.\n predicate\n A function that takes a data parameter to check for event\n properties. The data param...
Please provide a description of the function:async def identify(self): payload = { 'op': self.IDENTIFY, 'd': { 'token': self.token, 'properties': { '$os': sys.platform, '$browser': 'discord.py', ...
[ "Sends the IDENTIFY packet." ]
Please provide a description of the function:async def resume(self): payload = { 'op': self.RESUME, 'd': { 'seq': self.sequence, 'session_id': self.session_id, 'token': self.token } } await self.send_as...
[ "Sends the RESUME packet." ]
Please provide a description of the function:async def poll_event(self): try: msg = await self.recv() await self.received_message(msg) except websockets.exceptions.ConnectionClosed as exc: if self._can_handle_close(exc.code): log.info('Websock...
[ "Polls for a DISPATCH event and handles the general gateway loop.\n\n Raises\n ------\n ConnectionClosed\n The websocket connection was terminated for unhandled reasons.\n " ]
Please provide a description of the function:async def from_client(cls, client, *, resume=False): gateway = 'wss://' + client.endpoint + '/?v=4' ws = await websockets.connect(gateway, loop=client.loop, klass=cls, compression=None) ws.gateway = gateway ws._connection = client ...
[ "Creates a voice websocket for the :class:`VoiceClient`." ]
Please provide a description of the function:def clear(self): if self.prefix is not None: self._current_page = [self.prefix] self._count = len(self.prefix) + 1 # prefix + newline else: self._current_page = [] self._count = 0 self._pages = ...
[ "Clears the paginator to have no pages." ]
Please provide a description of the function:def add_line(self, line='', *, empty=False): max_page_size = self.max_size - self._prefix_len - 2 if len(line) > max_page_size: raise RuntimeError('Line exceeds maximum page size %s' % (max_page_size)) if self._count + len(line) ...
[ "Adds a line to the current page.\n\n If the line exceeds the :attr:`max_size` then an exception\n is raised.\n\n Parameters\n -----------\n line: :class:`str`\n The line to add.\n empty: :class:`bool`\n Indicates if another empty line should be added....
Please provide a description of the function:def close_page(self): if self.suffix is not None: self._current_page.append(self.suffix) self._pages.append('\n'.join(self._current_page)) if self.prefix is not None: self._current_page = [self.prefix] sel...
[ "Prematurely terminate a page." ]
Please provide a description of the function:def get_bot_mapping(self): bot = self.context.bot mapping = { cog: cog.get_commands() for cog in bot.cogs.values() } mapping[None] = [c for c in bot.all_commands.values() if c.cog is None] return mappin...
[ "Retrieves the bot mapping passed to :meth:`send_bot_help`." ]
Please provide a description of the function:def clean_prefix(self): user = self.context.guild.me if self.context.guild else self.context.bot.user # this breaks if the prefix mention is not the bot itself but I # consider this to be an *incredibly* strange use case. I'd rather go ...
[ "The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``." ]
Please provide a description of the function:def invoked_with(self): command_name = self._command_impl.name ctx = self.context if ctx is None or ctx.command is None or ctx.command.qualified_name != command_name: return command_name return ctx.invoked_with
[ "Similar to :attr:`Context.invoked_with` except properly handles\n the case where :meth:`Context.send_help` is used.\n\n If the help command was used regularly then this returns\n the :attr:`Context.invoked_with` attribute. Otherwise, if\n it the help command was called using :meth:`Cont...
Please provide a description of the function:def get_command_signature(self, command): parent = command.full_parent_name if len(command.aliases) > 0: aliases = '|'.join(command.aliases) fmt = '[%s|%s]' % (command.name, aliases) if parent: fmt...
[ "Retrieves the signature portion of the help page.\n\n Parameters\n ------------\n command: :class:`Command`\n The command to get the signature of.\n\n Returns\n --------\n :class:`str`\n The signature for the command.\n " ]
Please provide a description of the function:def remove_mentions(self, string): def replace(obj, *, transforms=self.MENTION_TRANSFORMS): return transforms.get(obj.group(0), '@invalid') return self.MENTION_PATTERN.sub(replace, string)
[ "Removes mentions from the string to prevent abuse.\n\n This includes ``@everyone``, ``@here``, member mentions and role mentions.\n " ]
Please provide a description of the function:def subcommand_not_found(self, command, string): if isinstance(command, Group) and len(command.all_commands) > 0: return 'Command "{0.qualified_name}" has no subcommand named {1}'.format(command, string) return 'Command "{0.qualified_name...
[ "|maybecoro|\n\n A method called when a command did not have a subcommand requested in the help command.\n This is useful to override for i18n.\n\n Defaults to either:\n\n - ``'Command \"{command.qualified_name}\" has no subcommands.'``\n - If there is no subcommand in the ``c...
Please provide a description of the function:async def filter_commands(self, commands, *, sort=False, key=None): if sort and key is None: key = lambda c: c.name iterator = commands if self.show_hidden else filter(lambda c: not c.hidden, commands) if not self.verify_checks...
[ "|coro|\n\n Returns a filtered list of commands and optionally sorts them.\n\n This takes into account the :attr:`verify_checks` and :attr:`show_hidden`\n attributes.\n\n Parameters\n ------------\n commands: Iterable[:class:`Command`]\n An iterable of commands t...
Please provide a description of the function:def get_max_size(self, commands): as_lengths = ( discord.utils._string_width(c.name) for c in commands ) return max(as_lengths, default=0)
[ "Returns the largest name length of the specified command list.\n\n Parameters\n ------------\n commands: Sequence[:class:`Command`]\n A sequence of commands to check for the largest size.\n\n Returns\n --------\n :class:`int`\n The maximum width of th...
Please provide a description of the function:async def command_callback(self, ctx, *, command=None): await self.prepare_help_command(ctx, command) bot = ctx.bot if command is None: mapping = self.get_bot_mapping() return await self.send_bot_help(mapping) ...
[ "|coro|\n\n The actual implementation of the help command.\n\n It is not recommended to override this method and instead change\n the behaviour through the methods that actually get dispatched.\n\n - :meth:`send_bot_help`\n - :meth:`send_cog_help`\n - :meth:`send_group_help...
Please provide a description of the function:def shorten_text(self, text): if len(text) > self.width: return text[:self.width - 3] + '...' return text
[ "Shortens text to fit into the :attr:`width`." ]
Please provide a description of the function:def add_indented_commands(self, commands, *, heading, max_size=None): if not commands: return self.paginator.add_line(heading) max_size = max_size or self.get_max_size(commands) get_width = discord.utils._string_width ...
[ "Indents a list of commands after the specified heading.\n\n The formatting is added to the :attr:`paginator`.\n\n The default implementation is the command name indented by\n :attr:`indent` spaces, padded to ``max_size`` followed by\n the command's :attr:`Command.short_doc` and then sho...
Please provide a description of the function:async def send_pages(self): destination = self.get_destination() for page in self.paginator.pages: await destination.send(page)
[ "A helper utility to send the page output from :attr:`paginator` to the destination." ]
Please provide a description of the function:def add_bot_commands_formatting(self, commands, heading): if commands: # U+2002 Middle Dot joined = '\u2002'.join(c.name for c in commands) self.paginator.add_line('__**%s**__' % heading) self.paginator.add_lin...
[ "Adds the minified bot heading with commands to the output.\n\n The formatting should be added to the :attr:`paginator`.\n\n The default implementation is a bold underline heading followed\n by commands separated by an EN SPACE (U+2002) in the next line.\n\n Parameters\n ---------...
Please provide a description of the function:def add_subcommand_formatting(self, command): fmt = '{0}{1} \N{EN DASH} {2}' if command.short_doc else '{0}{1}' self.paginator.add_line(fmt.format(self.clean_prefix, command.qualified_name, command.short_doc))
[ "Adds formatting information on a subcommand.\n\n The formatting should be added to the :attr:`paginator`.\n\n The default implementation is the prefix and the :attr:`Command.qualified_name`\n optionally followed by an En dash and the command's :attr:`Command.short_doc`.\n\n Parameters\n...
Please provide a description of the function:def add_aliases_formatting(self, aliases): self.paginator.add_line('**%s** %s' % (self.aliases_heading, ', '.join(aliases)), empty=True)
[ "Adds the formatting information on a command's aliases.\n\n The formatting should be added to the :attr:`paginator`.\n\n The default implementation is the :attr:`aliases_heading` bolded\n followed by a comma separated list of aliases.\n\n This is not called if there are no aliases to fo...
Please provide a description of the function:def add_command_formatting(self, command): if command.description: self.paginator.add_line(command.description, empty=True) signature = self.get_command_signature(command) if command.aliases: self.paginator.add_line(...
[ "A utility function to format commands and groups.\n\n Parameters\n ------------\n command: :class:`Command`\n The command to format.\n " ]
Please provide a description of the function:async def disconnect(self, *, force=False): if not force and not self.is_connected(): return self.stop() self._connected.clear() try: if self.ws: await self.ws.close() await self....
[ "|coro|\n\n Disconnects this voice client from voice.\n " ]
Please provide a description of the function:async def move_to(self, channel): guild_id, _ = self.channel._get_voice_state_pair() await self.main_ws.voice_state(guild_id, channel.id)
[ "|coro|\n\n Moves you to a different voice channel.\n\n Parameters\n -----------\n channel: :class:`abc.Snowflake`\n The channel to move to. Must be a voice channel.\n " ]
Please provide a description of the function:def play(self, source, *, after=None): if not self.is_connected(): raise ClientException('Not connected to voice.') if self.is_playing(): raise ClientException('Already playing audio.') if not isinstance(source, Aud...
[ "Plays an :class:`AudioSource`.\n\n The finalizer, ``after`` is called after the source has been exhausted\n or an error occurred.\n\n If an error happens while the audio player is running, the exception is\n caught and the audio player is then stopped.\n\n Parameters\n ---...
Please provide a description of the function:def send_audio_packet(self, data, *, encode=True): self.checked_add('sequence', 1, 65535) if encode: encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME) else: encoded_data = data packet = ...
[ "Sends an audio packet composed of the data.\n\n You must be connected to play audio.\n\n Parameters\n ----------\n data: bytes\n The :term:`py:bytes-like object` denoting PCM or Opus voice data.\n encode: bool\n Indicates if ``data`` should be encoded into O...
Please provide a description of the function:async def on_error(self, event_method, *args, **kwargs): print('Ignoring exception in {}'.format(event_method), file=sys.stderr) traceback.print_exc()
[ "|coro|\n\n The default error handler provided by the client.\n\n By default this prints to :data:`sys.stderr` however it could be\n overridden to have a different implementation.\n Check :func:`discord.on_error` for more details.\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.') await self._connection.request_offline_members(guilds)
[ "|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 login(self, token, *, bot=True): log.info('logging in using static token') await self.http.static_login(token, bot=bot) self._connection.is_bot = bot
[ "|coro|\n\n Logs in the client with the specified credentials.\n\n This function can be used in two different ways.\n\n .. warning::\n\n Logging on with a user token is against the Discord\n `Terms of Service <https://support.discordapp.com/hc/en-us/articles/115002192352>`...
Please provide a description of the function:async def connect(self, *, reconnect=True): backoff = ExponentialBackoff() while not self.is_closed(): try: await self._connect() except (OSError, HTTPException, Gateway...
[ "|coro|\n\n Creates a websocket connection and lets the websocket listen\n to messages from discord. This is a loop that runs the entire\n event system and miscellaneous aspects of the library. Control\n is not resumed until the WebSocket connection is terminated.\n\n Parameters\n...
Please provide a description of the function:async def close(self): if self._closed: return await self.http.close() self._closed = True for voice in self.voice_clients: try: await voice.disconnect() except Exception: ...
[ "|coro|\n\n Closes the connection to discord.\n " ]
Please provide a description of the function:def clear(self): self._closed = False self._ready.clear() self._connection.clear() self.http.recreate()
[ "Clears the internal state of the bot.\n\n After this, the bot can be considered \"re-opened\", i.e. :meth:`.is_closed`\n and :meth:`.is_ready` both return ``False`` along with the bot's internal\n cache cleared.\n " ]
Please provide a description of the function:async def start(self, *args, **kwargs): bot = kwargs.pop('bot', True) reconnect = kwargs.pop('reconnect', True) await self.login(*args, bot=bot) await self.connect(reconnect=reconnect)
[ "|coro|\n\n A shorthand coroutine for :meth:`login` + :meth:`connect`.\n " ]
Please provide a description of the function:def run(self, *args, **kwargs): async def runner(): try: await self.start(*args, **kwargs) finally: await self.close() try: self.loop.run_until_complete(runner()) except Key...
[ "A blocking call that abstracts away the event loop\n initialisation from you.\n\n If you want more control over the event loop then this\n function should not be used. Use :meth:`start` coroutine\n or :meth:`connect` + :meth:`login`.\n\n Roughly Equivalent to: ::\n\n t...
Please provide a description of the function:def wait_for(self, event, *, check=None, timeout=None): future = self.loop.create_future() if check is None: def _check(*args): return True check = _check ev = event.lower() try: l...
[ "|coro|\n\n Waits for a WebSocket event to be dispatched.\n\n This could be used to wait for a user to reply to a message,\n or to react to a message, or to edit a message in a self-contained\n way.\n\n The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default,...
Please provide a description of the function:def event(self, coro): if not asyncio.iscoroutinefunction(coro): raise TypeError('event registered must be a coroutine function') setattr(self, coro.__name__, coro) log.debug('%s has successfully been registered as an event', co...
[ "A decorator that registers an event to listen to.\n\n You can find more info about the events on the :ref:`documentation below <discord-api-events>`.\n\n The events must be a |corourl|_, if not, :exc:`TypeError` is raised.\n\n Example\n ---------\n\n .. code-block:: python3\n\n ...
Please provide a description of the function:async def change_presence(self, *, activity=None, status=None, afk=False): if status is None: status = 'online' status_enum = Status.online elif status is Status.offline: status = 'invisible' status_en...
[ "|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 ---...
Please provide a description of the function:def fetch_guilds(self, *, limit=100, before=None, after=None): return GuildIterator(self, limit=limit, before=before, after=after)
[ "|coro|\n\n Retrieves an :class:`.AsyncIterator` that enables receiving your guilds.\n\n .. note::\n\n Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`,\n :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`.\n\n .. note::\n\n ...
Please provide a description of the function:async def fetch_guild(self, guild_id): data = await self.http.get_guild(guild_id) return Guild(data=data, state=self._connection)
[ "|coro|\n\n Retrieves a :class:`.Guild` from an ID.\n\n .. note::\n\n Using this, you will not receive :attr:`.Guild.channels`, :class:`.Guild.members`,\n :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`.\n\n .. note::\n\n This method is a...
Please provide a description of the function:async def create_guild(self, name, region=None, icon=None): if icon is not None: icon = utils._bytes_to_base64_data(icon) if region is None: region = VoiceRegion.us_west.value else: region = region.value ...
[ "|coro|\n\n Creates a :class:`.Guild`.\n\n Bot accounts in more than 10 guilds are not allowed to create guilds.\n\n Parameters\n ----------\n name: :class:`str`\n The name of the guild.\n region: :class:`VoiceRegion`\n The region for the voice communi...
Please provide a description of the function:async def fetch_invite(self, url, *, with_counts=True): invite_id = utils.resolve_invite(url) data = await self.http.get_invite(invite_id, with_counts=with_counts) return Invite.from_incomplete(state=self._connection, data=data)
[ "|coro|\n\n Gets an :class:`.Invite` from a discord.gg URL or ID.\n\n .. note::\n\n If the invite is for a guild you have not joined, the guild and channel\n attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` and\n :class:`PartialInviteCha...
Please provide a description of the function:async def delete_invite(self, invite): invite_id = utils.resolve_invite(invite) await self.http.delete_invite(invite_id)
[ "|coro|\n\n Revokes an :class:`.Invite`, URL, or ID to an invite.\n\n You must have the :attr:`~.Permissions.manage_channels` permission in\n the associated guild to do this.\n\n Parameters\n ----------\n invite: Union[:class:`.Invite`, :class:`str`]\n The invite...
Please provide a description of the function:async def fetch_widget(self, guild_id): data = await self.http.get_widget(guild_id) return Widget(state=self._connection, data=data)
[ "|coro|\n\n Gets a :class:`.Widget` from a guild ID.\n\n .. note::\n\n The guild must have the widget enabled to get this information.\n\n Parameters\n -----------\n guild_id: :class:`int`\n The ID of the guild.\n\n Raises\n -------\n For...
Please provide a description of the function:async def application_info(self): data = await self.http.application_info() if 'rpc_origins' not in data: data['rpc_origins'] = None return AppInfo(self._connection, data)
[ "|coro|\n\n Retrieve's the bot's application information.\n\n Raises\n -------\n HTTPException\n Retrieving the information failed somehow.\n\n Returns\n --------\n :class:`.AppInfo`\n A namedtuple representing the application info.\n " ]
Please provide a description of the function:async def fetch_user(self, user_id): data = await self.http.get_user(user_id) return User(state=self._connection, data=data)
[ "|coro|\n\n Retrieves a :class:`~discord.User` based on their ID. This can only\n be used by bot accounts. You do not have to share any guilds\n with the user to get this information, however many operations\n do require that you do.\n\n .. note::\n\n This method is an ...
Please provide a description of the function:async def fetch_user_profile(self, user_id): state = self._connection data = await self.http.get_user_profile(user_id) def transform(d): return state._get_guild(int(d['id'])) since = data.get('premium_since') mu...
[ "|coro|\n\n Gets an arbitrary user's profile. This can only be used by non-bot accounts.\n\n Parameters\n ------------\n user_id: :class:`int`\n The ID of the user to fetch their profile for.\n\n Raises\n -------\n Forbidden\n Not allowed to fet...
Please provide a description of the function:async def fetch_webhook(self, webhook_id): data = await self.http.get_webhook(webhook_id) return Webhook.from_state(data, state=self._connection)
[ "|coro|\n\n Retrieves a :class:`.Webhook` with the specified ID.\n\n Raises\n --------\n HTTPException\n Retrieving the webhook failed.\n NotFound\n Invalid webhook ID.\n Forbidden\n You do not have permission to fetch this webhook.\n\n ...
Please provide a description of the function:def icon_url_as(self, *, format='webp', size=1024): return Asset._from_guild_image(self._state, self.id, self.icon, 'icons', format=format, size=size)
[ ":class:`Asset`: The same operation as :meth:`Guild.icon_url_as`." ]
Please provide a description of the function:def banner_url_as(self, *, format='webp', size=2048): return Asset._from_guild_image(self._state, self.id, self.banner, 'banners', format=format, size=size)
[ ":class:`Asset`: The same operation as :meth:`Guild.banner_url_as`." ]
Please provide a description of the function:def splash_url_as(self, *, format='webp', size=2048): return Asset._from_guild_image(self._state, self.id, self.splash, 'splashes', format=format, size=size)
[ ":class:`Asset`: The same operation as :meth:`Guild.splash_url_as`." ]
Please provide a description of the function:async def delete(self, *, reason=None): await self._state.http.delete_invite(self.code, reason=reason)
[ "|coro|\n\n Revokes the instant invite.\n\n You must have the :attr:`~Permissions.manage_channels` permission to do this.\n\n Parameters\n -----------\n reason: Optional[:class:`str`]\n The reason for deleting this invite. Shows up on the audit log.\n\n Raises\n ...
Please provide a description of the function:async def save(self, fp, *, seek_begin=True, use_cached=False): url = self.proxy_url if use_cached else self.url data = await self._http.get_from_cdn(url) if isinstance(fp, io.IOBase) and fp.writable(): written = fp.write(data) ...
[ "|coro|\n\n Saves this attachment into a file-like object.\n\n Parameters\n -----------\n fp: Union[BinaryIO, :class:`os.PathLike`]\n The file-like object to save this attachment to or the filename\n to use. If a filename is passed then a file is created with that\n...
Please provide a description of the function:def raw_mentions(self): return [int(x) for x in re.findall(r'<@!?([0-9]+)>', self.content)]
[ "A property that returns an array of user IDs matched with\n the syntax of <@user_id> in the message content.\n\n This allows you to receive the user IDs of mentioned users\n even in a private message context.\n " ]
Please provide a description of the function:def raw_channel_mentions(self): return [int(x) for x in re.findall(r'<#([0-9]+)>', self.content)]
[ "A property that returns an array of channel IDs matched with\n the syntax of <#channel_id> in the message content.\n " ]
Please provide a description of the function:def raw_role_mentions(self): return [int(x) for x in re.findall(r'<@&([0-9]+)>', self.content)]
[ "A property that returns an array of role IDs matched with\n the syntax of <@&role_id> in the message content.\n " ]
Please provide a description of the function:def clean_content(self): transformations = { re.escape('<#%s>' % channel.id): '#' + channel.name for channel in self.channel_mentions } mention_transforms = { re.escape('<@%s>' % member.id): '@' + member....
[ "A property that returns the content in a \"cleaned up\"\n manner. This basically means that mentions are transformed\n into the way the client shows it. e.g. ``<#id>`` will transform\n into ``#name``.\n\n This will also transform @everyone and @here mentions into\n non-mentions.\...
Please provide a description of the function:def system_content(self): r if self.type is MessageType.default: return self.content if self.type is MessageType.pins_add: return '{0.name} pinned a message to this channel.'.format(self.author) if self.type is Messa...
[ "A property that returns the content that is rendered\n regardless of the :attr:`Message.type`.\n\n In the case of :attr:`MessageType.default`\\, this just returns the\n regular :attr:`Message.content`. Otherwise this returns an English\n message denoting the contents of the system messa...