Utility Functions

General Utility

redbot.core.utils.deduplicate_iterables(*iterables)[source]

Returns a list of all unique items in iterables, in the order they were first encountered.

redbot.core.utils.bounded_gather(*coros_or_futures, loop=None, return_exceptions=False, limit=4, semaphore=None)[source]

A semaphore-bounded wrapper to asyncio.gather().

Parameters:
  • *coros_or_futures – The awaitables to run in a bounded concurrent fashion.
  • loop (asyncio.AbstractEventLoop) – The event loop to use for the semaphore and asyncio.gather().
  • return_exceptions (bool) – If true, gather exceptions in the result list instead of raising.
  • limit (Optional[int]) – The maximum number of concurrent tasks. Used when no semaphore is passed.
  • semaphore (Optional[asyncio.Semaphore]) – The semaphore to use for bounding tasks. If None, create one using loop and limit.
Raises:

TypeError – When invalid parameters are passed

redbot.core.utils.bounded_gather_iter(*coros_or_futures, loop=None, limit=4, semaphore=None)[source]

An iterator that returns tasks as they are ready, but limits the number of tasks running at a time.

Parameters:
  • *coros_or_futures – The awaitables to run in a bounded concurrent fashion.
  • loop (asyncio.AbstractEventLoop) – The event loop to use for the semaphore and asyncio.gather().
  • limit (Optional[int]) – The maximum number of concurrent tasks. Used when no semaphore is passed.
  • semaphore (Optional[asyncio.Semaphore]) – The semaphore to use for bounding tasks. If None, create one using loop and limit.
Raises:

TypeError – When invalid parameters are passed

Chat Formatting

redbot.core.utils.chat_formatting.bold(text)[source]

Get the given text in bold.

Parameters:text (str) – The text to be marked up.
Returns:The marked up text.
Return type:str
redbot.core.utils.chat_formatting.bordered(*columns, ascii_border=False)[source]

Get two blocks of text in a borders.

Note

This will only work with a monospaced font.

Parameters:
  • *columns (sequence of str) – The columns of text, each being a list of lines in that column.
  • ascii_border (bool) – Whether or not the border should be pure ASCII.
Returns:

The bordered text.

Return type:

str

redbot.core.utils.chat_formatting.box(text, lang='')[source]

Get the given text in a code block.

Parameters:
  • text (str) – The text to be marked up.
  • lang (str, optional) – The syntax highlighting language for the codeblock.
Returns:

The marked up text.

Return type:

str

redbot.core.utils.chat_formatting.error(text)[source]

Get text prefixed with an error emoji.

Returns:The new message.
Return type:str
redbot.core.utils.chat_formatting.escape(text, *, mass_mentions=False, formatting=False)[source]

Get text with all mass mentions or markdown escaped.

Parameters:
  • text (str) – The text to be escaped.
  • mass_mentions (bool, optional) – Set to True to escape mass mentions in the text.
  • formatting (bool, optional) – Set to True to escpae any markdown formatting in the text.
Returns:

The escaped text.

Return type:

str

redbot.core.utils.chat_formatting.format_perms_list(perms)[source]

Format a list of permission names.

This will return a humanized list of the names of all enabled permissions in the provided discord.Permissions object.

Parameters:perms (discord.Permissions) – The permissions object with the requested permissions to list enabled.
Returns:The humanized list.
Return type:str
redbot.core.utils.chat_formatting.humanize_list(items)[source]

Get comma-separted list, with the last element joined with and.

This uses an Oxford comma, because without one, items containing the word and would make the output difficult to interpret.

Parameters:items (Sequence[str]) – The items of the list to join together.
Raises:IndexError – An empty sequence was passed

Examples

>>> humanize_list(['One', 'Two', 'Three'])
'One, Two, and Three'
>>> humanize_list(['One'])
'One'
redbot.core.utils.chat_formatting.humanize_number(val, override_locale=None)[source]

Convert an int or float to a str with digit separators based on bot locale

Parameters:
  • val (Union[int, float]) – The int/float to be formatted.
  • override_locale (Optional[str]) – A value to override the bots locale.
Returns:

locale aware formatted number.

Return type:

str

redbot.core.utils.chat_formatting.humanize_timedelta(*, timedelta=None, seconds=None)[source]

Get a locale aware human timedelta representation.

This works with either a timedelta object or a number of seconds.

Fractional values will be omitted, and values less than 1 second an empty string.

Parameters:
  • timedelta (Optional[datetime.timedelta]) – A timedelta object
  • seconds (Optional[SupportsInt]) – A number of seconds
Returns:

A locale aware representation of the timedelta or seconds.

Return type:

str

Raises:

ValueError – The function was called with neither a number of seconds nor a timedelta object

redbot.core.utils.chat_formatting.info(text)[source]

Get text prefixed with an info emoji.

Returns:The new message.
Return type:str
redbot.core.utils.chat_formatting.inline(text)[source]

Get the given text as inline code.

Parameters:text (str) – The text to be marked up.
Returns:The marked up text.
Return type:str
redbot.core.utils.chat_formatting.italics(text)[source]

Get the given text in italics.

Parameters:text (str) – The text to be marked up.
Returns:The marked up text.
Return type:str
for ... in redbot.core.utils.chat_formatting.pagify(text, delims=['\n'], *, priority=False, escape_mass_mentions=True, shorten_by=8, page_length=2000)[source]

Generate multiple pages from the given text.

Note

This does not respect code blocks or inline code.

Parameters:
  • text (str) – The content to pagify and send.
  • delims (sequence of str, optional) – Characters where page breaks will occur. If no delimiters are found in a page, the page will break after page_length characters. By default this only contains the newline.
Other Parameters:
 
  • priority (bool) – Set to True to choose the page break delimiter based on the order of delims. Otherwise, the page will always break at the last possible delimiter.
  • escape_mass_mentions (bool) – If True, any mass mentions (here or everyone) will be silenced.
  • shorten_by (int) – How much to shorten each page by. Defaults to 8.
  • page_length (int) – The maximum length of each page. Defaults to 2000.
Yields:

str – Pages of the given text.

redbot.core.utils.chat_formatting.question(text)[source]

Get text prefixed with a question emoji.

Returns:The new message.
Return type:str
redbot.core.utils.chat_formatting.strikethrough(text)[source]

Get the given text with a strikethrough.

Parameters:text (str) – The text to be marked up.
Returns:The marked up text.
Return type:str
redbot.core.utils.chat_formatting.text_to_file(text, filename='file.txt', *, spoiler=False, encoding='utf-8')[source]

Prepares text to be sent as a file on Discord, without character limit.

This writes text into a bytes object that can be used for the file or files parameters of discord.abc.Messageable.send().

Parameters:
  • text (str) – The text to put in your file.
  • filename (str) – The name of the file sent. Defaults to file.txt.
  • spoiler (bool) – Whether the attachment is a spoiler. Defaults to False.
Returns:

The file containing your text.

Return type:

discord.File

redbot.core.utils.chat_formatting.underline(text)[source]

Get the given text with an underline.

Parameters:text (str) – The text to be marked up.
Returns:The marked up text.
Return type:str
redbot.core.utils.chat_formatting.warning(text)[source]

Get text prefixed with a warning emoji.

Returns:The new message.
Return type:str

Embed Helpers

redbot.core.utils.embed.randomize_color(embed)

Gives the provided embed a random color. There is an alias for this called randomize_color

Parameters:embed (discord.Embed) – The embed to add a color to
Returns:The embed with the color set to a random color
Return type:discord.Embed
redbot.core.utils.embed.randomize_colour(embed)[source]

Gives the provided embed a random color. There is an alias for this called randomize_color

Parameters:embed (discord.Embed) – The embed to add a color to
Returns:The embed with the color set to a random color
Return type:discord.Embed

Reaction Menus

await redbot.core.utils.menus.menu(ctx, pages, controls, message=None, page=0, timeout=30.0)[source]

An emoji-based menu

Note

All pages should be of the same type

Note

All functions for handling what a particular emoji does should be coroutines (i.e. async def). Additionally, they must take all of the parameters of this function, in addition to a string representing the emoji reacted with. This parameter should be the last one, and none of the parameters in the handling functions are optional

Parameters:
  • ctx (commands.Context) – The command context
  • pages (list of str or discord.Embed) – The pages of the menu.
  • controls (dict) – A mapping of emoji to the function which handles the action for the emoji.
  • message (discord.Message) – The message representing the menu. Usually None when first opening the menu
  • page (int) – The current page number of the menu
  • timeout (float) – The time (in seconds) to wait for a reaction
Raises:

RuntimeError – If either of the notes above are violated

redbot.core.utils.menus.start_adding_reactions(message, emojis, loop=None)[source]

Start adding reactions to a message.

This is a non-blocking operation - calling this will schedule the reactions being added, but the calling code will continue to execute asynchronously. There is no need to await this function.

This is particularly useful if you wish to start waiting for a reaction whilst the reactions are still being added - in fact, this is exactly what menu uses to do that.

This spawns a asyncio.Task object and schedules it on loop. If loop omitted, the loop will be retrieved with asyncio.get_event_loop.

Parameters:
Returns:

The task for the coroutine adding the reactions.

Return type:

asyncio.Task

Event Predicates

class redbot.core.utils.predicates.MessagePredicate(predicate)[source]

Bases: collections.abc.Callable, typing.Generic

A simple collection of predicates for message events.

These predicates intend to help simplify checks in message events and reduce boilerplate code.

This class should be created through the provided classmethods. Instances of this class are callable message predicates, i.e. they return True if a message matches the criteria.

All predicates are combined with MessagePredicate.same_context().

Examples

Waiting for a response in the same channel and from the same author:

await bot.wait_for("message", check=MessagePredicate.same_context(ctx))

Waiting for a response to a yes or no question:

pred = MessagePredicate.yes_or_no(ctx)
await bot.wait_for("message", check=pred)
if pred.result is True:
    # User responded "yes"
    ...

Getting a member object from a user’s response:

pred = MessagePredicate.valid_member(ctx)
await bot.wait_for("message", check=pred)
member = pred.result
result

The object which the message content matched with. This is dependent on the predicate used - see each predicate’s documentation for details, not every method will assign this attribute. Defaults to None.

Type:Any
classmethod cancelled(ctx=None, channel=None, user=None)[source]

Match if the message is [p]cancel.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod contained_in(collection, ctx=None, channel=None, user=None)[source]

Match if the response is contained in the specified collection.

The index of the response in the collection sequence is assigned to the result attribute.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod equal_to(value, ctx=None, channel=None, user=None)[source]

Match if the response is equal to the specified value.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod greater(value, ctx=None, channel=None, user=None)[source]

Match if the response is greater than the specified value.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod has_role(ctx=None, channel=None, user=None)[source]

Match if the response refers to a role which the author has.

Assigns the matching discord.Role object to result.

One of user or ctx must be supplied. This predicate cannot be used in DM.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod length_greater(length, ctx=None, channel=None, user=None)[source]

Match if the response’s length is greater than the specified length.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod length_less(length, ctx=None, channel=None, user=None)[source]

Match if the response’s length is less than the specified length.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod less(value, ctx=None, channel=None, user=None)[source]

Match if the response is less than the specified value.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod lower_contained_in(collection, ctx=None, channel=None, user=None)[source]

Same as contained_in(), but the response is set to lowercase before matching.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod lower_equal_to(value, ctx=None, channel=None, user=None)[source]

Match if the response as lowercase is equal to the specified value.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod positive(ctx=None, channel=None, user=None)[source]

Match if the response is a positive number.

Assigns the response to result as a float.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod regex(pattern, ctx=None, channel=None, user=None)[source]

Match if the response matches the specified regex pattern.

This predicate will use re.search to find a match. The resulting match object will be assigned to result.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod same_context(ctx=None, channel=None, user=None)[source]

Match if the reaction fits the described context.

Parameters:
  • ctx (Optional[Context]) – The current invokation context.
  • channel (Optional[discord.TextChannel]) – The channel we expect a message in. If unspecified, defaults to ctx.channel. If ctx is unspecified too, the message’s channel will be ignored.
  • user (Optional[discord.abc.User]) – The user we expect a message from. If unspecified, defaults to ctx.author. If ctx is unspecified too, the message’s author will be ignored.
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod valid_float(ctx=None, channel=None, user=None)[source]

Match if the response is a float.

Assigns the response to result as a float.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod valid_int(ctx=None, channel=None, user=None)[source]

Match if the response is an integer.

Assigns the response to result as an int.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod valid_member(ctx=None, channel=None, user=None)[source]

Match if the response refers to a member in the current guild.

Assigns the matching discord.Member object to result.

This predicate cannot be used in DM.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod valid_role(ctx=None, channel=None, user=None)[source]

Match if the response refers to a role in the current guild.

Assigns the matching discord.Role object to result.

This predicate cannot be used in DM.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod valid_text_channel(ctx=None, channel=None, user=None)[source]

Match if the response refers to a text channel in the current guild.

Assigns the matching discord.TextChannel object to result.

This predicate cannot be used in DM.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

classmethod yes_or_no(ctx=None, channel=None, user=None)[source]

Match if the message is “yes”/”y” or “no”/”n”.

This will assign True for yes, or False for no to the result attribute.

Parameters:
Returns:

The event predicate.

Return type:

MessagePredicate

class redbot.core.utils.predicates.ReactionPredicate(predicate)[source]

Bases: collections.abc.Callable, typing.Generic

A collection of predicates for reaction events.

All checks are combined with ReactionPredicate.same_context().

Examples

Confirming a yes/no question with a tick/cross reaction:

from redbot.core.utils.predicates import ReactionPredicate
from redbot.core.utils.menus import start_adding_reactions

msg = await ctx.send("Yes or no?")
start_adding_reactions(msg, ReactionPredicate.YES_OR_NO_EMOJIS)

pred = ReactionPredicate.yes_or_no(msg, ctx.author)
await ctx.bot.wait_for("reaction_add", check=pred)
if pred.result is True:
    # User responded with tick
    ...
else:
    # User responded with cross
    ...

Waiting for the first reaction from any user with one of the first 5 letters of the alphabet:

from redbot.core.utils.predicates import ReactionPredicate
from redbot.core.utils.menus import start_adding_reactions

msg = await ctx.send("React to me!")
emojis = ReactionPredicate.ALPHABET_EMOJIS[:5]
start_adding_reactions(msg, emojis)

pred = ReactionPredicate.with_emojis(emojis, msg)
await ctx.bot.wait_for("reaction_add", check=pred)
# pred.result is now the index of the letter in `emojis`
result

The object which the message content matched with. This is dependent on the predicate used - see each predicate’s documentation for details, not every method will assign this attribute. Defaults to None.

Type:Any
ALPHABET_EMOJIS = ['🇦', '🇧', '🇨', '🇩', '🇪', '🇫', '🇬', '🇭', '🇮', '🇯', '🇰', '🇱', '🇲', '🇳', '🇴', '🇵', '🇶', '🇷', '🇸', '🇹', '🇺', '🇻', '🇼', '🇽', '🇾', '🇿']

A list of all 26 alphabetical letter emojis.

Type:List[str]
NUMBER_EMOJIS = ['0⃣', '1⃣', '2⃣', '3⃣', '4⃣', '5⃣', '6⃣', '7⃣', '8⃣', '9⃣']

A list of all single-digit number emojis, 0 through 9.

Type:List[str]
YES_OR_NO_EMOJIS = ('✅', '❎')

A tuple containing the tick emoji and cross emoji, in that order.

Type:Tuple[str, str]
classmethod same_context(message=None, user=None)[source]

Match if a reaction fits the described context.

This will ignore reactions added by the bot user, regardless of whether or not user is supplied.

Parameters:
  • message (Optional[discord.Message]) – The message which we expect a reaction to. If unspecified, the reaction’s message will be ignored.
  • user (Optional[discord.abc.User]) – The user we expect to react. If unspecified, the user who added the reaction will be ignored.
Returns:

The event predicate.

Return type:

ReactionPredicate

classmethod with_emojis(emojis, message=None, user=None)[source]

Match if the reaction is one of the specified emojis.

Parameters:
Returns:

The event predicate.

Return type:

ReactionPredicate

classmethod yes_or_no(message=None, user=None)[source]

Match if the reaction is a tick or cross emoji.

The emojis used can are in ReactionPredicate.YES_OR_NO_EMOJIS.

This will assign True for yes, or False for no to the result attribute.

Parameters:
Returns:

The event predicate.

Return type:

ReactionPredicate

Mod Helpers

await redbot.core.utils.mod.check_permissions(ctx, perms)[source]

Check if the author has required permissions.

This will always return True if the author is a bot owner, or has the administrator permission. If perms is empty, this will only check if the user is a bot owner.

Parameters:
  • ctx (Context) – The command invokation context to check.
  • perms (Dict[str, bool]) – A dictionary mapping permissions to their required states. Valid permission names are those listed as properties of the discord.Permissions class.
Returns:

True if the author has the required permissions.

Return type:

bool

redbot.core.utils.mod.get_audit_reason(author, reason=None)[source]

Construct a reason to appear in the audit log.

Parameters:
  • author (discord.Member) – The author behind the audit log action.
  • reason (str) – The reason behind the audit log action.
Returns:

The formatted audit log reason.

Return type:

str

await redbot.core.utils.mod.is_admin_or_superior(bot, obj)[source]

Same as is_mod_or_superior except for admin permissions.

If a message is passed, its author’s permissions are checked. If a role is passed, it simply checks if it is the admin role.

Parameters:
Returns:

True if the object has admin permissions.

Return type:

bool

Raises:

TypeError – If the wrong type of obj was passed.

await redbot.core.utils.mod.is_mod_or_superior(bot, obj)[source]

Check if an object has mod or superior permissions.

If a message is passed, its author’s permissions are checked. If a role is passed, it simply checks if it is one of either the admin or mod roles.

Parameters:
Returns:

True if the object has mod permissions.

Return type:

bool

Raises:

TypeError – If the wrong type of obj was passed.

await redbot.core.utils.mod.mass_purge(messages, channel)[source]

Bulk delete messages from a channel.

If more than 100 messages are supplied, the bot will delete 100 messages at a time, sleeping between each action.

Note

Messages must not be older than 14 days, and the bot must not be a user account.

Parameters:
Raises:
await redbot.core.utils.mod.slow_deletion(messages)[source]

Delete a list of messages one at a time.

Any exceptions raised when trying to delete the message will be silenced.

Parameters:messages (iterable of discord.Message) – The messages to delete.
redbot.core.utils.mod.strfdelta(delta)[source]

Format a timedelta object to a message with time units.

Parameters:delta (datetime.timedelta) – The duration to parse.
Returns:A message representing the timedelta with units.
Return type:str

Tunnel

class redbot.core.utils.tunnel.Tunnel(*, sender, origin, recipient)[source]

Bases: object

A tunnel interface for messages

This will return None on init if the destination or source + origin pair is already in use, or the existing tunnel object if one exists for the designated parameters

sender

The person who opened the tunnel

Type:discord.Member
origin

The channel in which it was opened

Type:discord.TextChannel
recipient

The user on the other end of the tunnel

Type:discord.User
await communicate(*, message, topic=None, skip_message_content=False)[source]

Forwards a message.

Parameters:
  • message (discord.Message) – The message to forward
  • topic (str) – A string to prepend
  • skip_message_content (bool) – If this flag is set, only the topic will be sent
Returns:

a pair of ints matching the ids of the message which was forwarded and the last message the bot sent to do that. useful if waiting for reactions.

Return type:

int, int

Raises:

discord.Forbidden – This should only happen if the user’s DMs are disabled the bot can’t upload at the origin channel or can’t add reactions there.

staticmethod await files_from_attach(m)[source]

makes a list of file objects from a message returns an empty list if none, or if the sum of file sizes is too large for the bot to send

Parameters:m (discord.Message) – A message to get attachments from
Returns:A list of discord.File objects
Return type:list of discord.File
staticmethod await files_from_attatch(m)

makes a list of file objects from a message returns an empty list if none, or if the sum of file sizes is too large for the bot to send

Parameters:m (discord.Message) – A message to get attachments from
Returns:A list of discord.File objects
Return type:list of discord.File
staticmethod await message_forwarder(*, destination, content=None, embed=None, files=None)[source]

This does the actual sending, use this instead of a full tunnel if you are using command initiated reactions instead of persistent event based ones

Parameters:
Returns:

The messages sent as a result.

Return type:

List[discord.Message]

Raises:

Common Filters

redbot.core.utils.common_filters.filter_urls(to_filter)[source]

Get a string with URLs sanitized.

This will match any URLs starting with these protocols:

  • http://
  • https://
  • ftp://
  • sftp://
Parameters:to_filter (str) – The string to filter.
Returns:The sanitized string.
Return type:str
redbot.core.utils.common_filters.filter_invites(to_filter)[source]

Get a string with discord invites sanitized.

Will match any discord.gg, discordapp.com/invite, or discord.me invite URL.

Parameters:to_filter (str) – The string to filter.
Returns:The sanitized string.
Return type:str
redbot.core.utils.common_filters.filter_mass_mentions(to_filter)[source]

Get a string with mass mentions sanitized.

Will match any here and/or everyone mentions.

Parameters:to_filter (str) – The string to filter.
Returns:The sanitized string.
Return type:str
redbot.core.utils.common_filters.filter_various_mentions(to_filter)[source]

Get a string with role, user, and channel mentions sanitized.

This is mainly for use on user display names, not message content, and should be applied sparingly.

Parameters:to_filter (str) – The string to filter.
Returns:The sanitized string.
Return type:str
redbot.core.utils.common_filters.normalize_smartquotes(to_normalize)[source]

Get a string with smart quotes replaced with normal ones

Parameters:to_normalize (str) – The string to normalize.
Returns:The normalized string.
Return type:str
redbot.core.utils.common_filters.escape_spoilers(content)[source]

Get a string with spoiler syntax escaped.

Parameters:content (str) – The string to escape.
Returns:The escaped string.
Return type:str
redbot.core.utils.common_filters.escape_spoilers_and_mass_mentions(content)[source]

Get a string with spoiler syntax and mass mentions escaped

Parameters:content (str) – The string to escape.
Returns:The escaped string.
Return type:str