Utility Functions¶
General Utility¶
-
redbot.core.utils.bounded_gather(*coros_or_futures, 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.
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 nosemaphoreis passed.semaphore (Optional[
asyncio.Semaphore]) – The semaphore to use for bounding tasks. IfNone, create one usingloopandlimit.
- Raises
TypeError – When invalid parameters are passed
-
redbot.core.utils.bounded_gather_iter(*coros_or_futures, 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.
limit (Optional[
int]) – The maximum number of concurrent tasks. Used when nosemaphoreis passed.semaphore (Optional[
asyncio.Semaphore]) – The semaphore to use for bounding tasks. IfNone, create one usingloopandlimit.
- Raises
TypeError – When invalid parameters are passed
-
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.get_end_user_data_statement(file)[source]¶ This function attempts to get the
end_user_data_statementkey from cog’sinfo.json. This will log the reason ifNoneis returned.- Parameters
file (Union[pathlib.Path, str]) – The
__file__variable for the cog’s__init__.pyfile.- Returns
The end user data statement found in the info.json or
Noneif there was an issue finding one.- Return type
Optional[str]
Examples
>>> # In cog's `__init__.py` >>> from redbot.core.utils import get_end_user_data_statement >>> __red_end_user_data_statement__ = get_end_user_data_statement(__file__) >>> def setup(bot): ... ...
-
redbot.core.utils.get_end_user_data_statement_or_raise(file)[source]¶ This function attempts to get the
end_user_data_statementkey from cog’sinfo.json.- Parameters
file (Union[pathlib.Path, str]) – The
__file__variable for the cog’s__init__.pyfile.- Returns
The end user data statement found in the info.json.
- Return type
- Raises
FileNotFoundError – When
info.jsondoes not exist.KeyError – When
info.jsondoes not have theend_user_data_statementkey.json.JSONDecodeError – When
info.jsoncan’t be decoded withjson.load()UnicodeError – When
info.jsoncan’t be decoded due to bad encoding.Exception – Any other exception raised from
pathlibandjsonmodules when attempting to parse theinfo.jsonfor theend_user_data_statementkey.
-
class
redbot.core.utils.AsyncIter(iterable, delay=0, steps=1)[source]¶ Bases:
AsyncIterator[redbot.core.utils._T],Awaitable[List[redbot.core.utils._T]]Asynchronous iterator yielding items from
iterablethat sleeps fordelayseconds everystepsitems.- Parameters
- Raises
ValueError – When
stepsis lower than 1.
Examples
>>> from redbot.core.utils import AsyncIter >>> async for value in AsyncIter(range(3)): ... print(value) 0 1 2
-
async for ... in
enumerate(start=0)[source]¶ Async iterable version of
enumerate.- Parameters
start (int) – The index to start from. Defaults to 0.
- Returns
An async iterator of tuples in the form of
(index, item).- Return type
AsyncIterator[Tuple[int, T]]
Examples
>>> from redbot.core.utils import AsyncIter >>> iterator = AsyncIter(['one', 'two', 'three']) >>> async for i in iterator.enumerate(start=10): ... print(i) (10, 'one') (11, 'two') (12, 'three')
-
async for ... in
filter(function)[source]¶ Filter the iterable with an (optionally async) predicate.
- Parameters
function (Callable[[T], Union[bool, Awaitable[bool]]]) – A function or coroutine function which takes one item of
iterableas an argument, and returnsTrueorFalse.- Returns
An object which can either be awaited to yield a list of the filtered items, or can also act as an async iterator to yield items one by one.
- Return type
AsyncFilter[T]
Examples
>>> from redbot.core.utils import AsyncIter >>> def predicate(value): ... return value <= 5 >>> iterator = AsyncIter([1, 10, 5, 100]) >>> async for i in iterator.filter(predicate): ... print(i) 1 5
>>> from redbot.core.utils import AsyncIter >>> def predicate(value): ... return value <= 5 >>> iterator = AsyncIter([1, 10, 5, 100]) >>> await iterator.filter(predicate) [1, 5]
-
__await__()[source]¶ Returns a list of the iterable.
Examples
>>> from redbot.core.utils import AsyncIter >>> iterator = AsyncIter(range(5)) >>> await iterator [0, 1, 2, 3, 4]
-
await
find(predicate, default=None)[source]¶ Calls
predicateover items in iterable and return first value to match.- Parameters
predicate (Union[Callable, Coroutine]) – A function that returns a boolean-like result. The predicate provided can be a coroutine.
default (Optional[Any]) – The value to return if there are no matches.
- Raises
TypeError – When
predicateis not a callable.
Examples
>>> from redbot.core.utils import AsyncIter >>> await AsyncIter(range(3)).find(lambda x: x == 1) 1
-
await
flatten()[source]¶ Returns a list of the iterable.
Examples
>>> from redbot.core.utils import AsyncIter >>> iterator = AsyncIter(range(5)) >>> await iterator.flatten() [0, 1, 2, 3, 4]
-
map(func)[source]¶ Set the mapping callable for this instance of
AsyncIter.Important
This should be called after AsyncIter initialization and before any other of its methods.
- Parameters
func (Union[Callable, Coroutine]) – The function to map values to. The function provided can be a coroutine.
- Raises
TypeError – When
funcis not a callable.
Examples
>>> from redbot.core.utils import AsyncIter >>> async for value in AsyncIter(range(3)).map(bool): ... print(value) False True True
-
await
next(default=Ellipsis)[source]¶ Returns a next entry of the iterable.
- Parameters
default (Optional[Any]) – The value to return if the iterator is exhausted.
- Raises
StopAsyncIteration – When
defaultis not specified and the iterator has been exhausted.
Examples
>>> from redbot.core.utils import AsyncIter >>> iterator = AsyncIter(range(5)) >>> await iterator.next() 0 >>> await iterator.next() 1
Chat Formatting¶
-
redbot.core.utils.chat_formatting.bold(text, escape_formatting=True)[source]¶ Get the given text in bold.
Note: By default, this function will escape
textprior to emboldening.
-
redbot.core.utils.chat_formatting.bordered(*columns, ascii_border=False)[source]¶ Get two blocks of text inside borders.
Note
This will only work with a monospaced font.
-
redbot.core.utils.chat_formatting.error(text)[source]¶ Get text prefixed with an error emoji.
- Returns
The new message.
- Return type
-
redbot.core.utils.chat_formatting.escape(text, *, mass_mentions=False, formatting=False)[source]¶ Get text with all mass mentions or markdown escaped.
-
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.Permissionsobject.- Parameters
perms (discord.Permissions) – The permissions object with the requested permissions to list enabled.
- Returns
The humanized list.
- Return type
-
redbot.core.utils.chat_formatting.humanize_list(items, *, locale=None, style='standard')[source]¶ Get comma-separated list, with the last element joined with and.
- Parameters
items (Sequence[str]) – The items of the list to join together.
locale (Optional[str]) – The locale to convert, if not specified it defaults to the bot’s locale.
style (str) –
The style to format the list with.
Note: Not all styles are necessarily available in all locales, see documentation of
babel.lists.format_listfor more details.- standard
A typical ‘and’ list for arbitrary placeholders. eg. “January, February, and March”
- standard-short
A short version of a ‘and’ list, suitable for use with short or abbreviated placeholder values. eg. “Jan., Feb., and Mar.”
- or
A typical ‘or’ list for arbitrary placeholders. eg. “January, February, or March”
- or-short
A short version of an ‘or’ list. eg. “Jan., Feb., or Mar.”
- unit
A list suitable for wide units. eg. “3 feet, 7 inches”
- unit-short
A list suitable for short units eg. “3 ft, 7 in”
- unit-narrow
A list suitable for narrow units, where space on the screen is very limited. eg. “3′ 7″”
- Raises
ValueError – The locale does not support the specified style.
Examples
>>> humanize_list(['One', 'Two', 'Three']) 'One, Two, and Three' >>> humanize_list(['One']) 'One' >>> humanize_list(['omena', 'peruna', 'aplari'], style='or', locale='fi') 'omena, peruna tai aplari'
-
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
-
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
- 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
-
redbot.core.utils.chat_formatting.italics(text, escape_formatting=True)[source]¶ Get the given text in italics.
Note: By default, this function will escape
textprior to italicising.
-
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
- Other Parameters
priority (
bool) – Set toTrueto choose the page break delimiter based on the order ofdelims. Otherwise, the page will always break at the last possible delimiter.escape_mass_mentions (
bool) – IfTrue, 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
-
redbot.core.utils.chat_formatting.spoiler(text, escape_formatting=True)[source]¶ Get the given text as a spoiler.
Note: By default, this function will escape
textprior to making the text a spoiler.
-
redbot.core.utils.chat_formatting.strikethrough(text, escape_formatting=True)[source]¶ Get the given text with a strikethrough.
Note: By default, this function will escape
textprior to applying a strikethrough.
-
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
fileorfilesparameters ofdiscord.abc.Messageable.send().- Parameters
- Returns
The file containing your text.
- Return type
Embed Helpers¶
-
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
Event Predicates¶
MessagePredicate¶
-
class
redbot.core.utils.predicates.MessagePredicate(predicate)[source]¶ Bases:
Callable[[discord.message.Message],bool]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
Trueif 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
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
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
collectionsequence is assigned to theresultattribute.- Parameters
collection (Sequence[str]) – The collection containing valid responses.
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
classmethod
equal_to(value, ctx=None, channel=None, user=None)[source]¶ Match if the response is equal to the specified value.
- Parameters
value (str) – The value to compare the response with.
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
classmethod
greater(value, ctx=None, channel=None, user=None)[source]¶ Match if the response is greater than the specified value.
- Parameters
value (Union[int, float]) – The value to compare the response with.
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
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.Roleobject toresult.One of
userorctxmust be supplied. This predicate cannot be used in DM.- Parameters
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
classmethod
length_greater(length, ctx=None, channel=None, user=None)[source]¶ Match if the response’s length is greater than the specified length.
- Parameters
length (int) – The value to compare the response’s length with.
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
classmethod
length_less(length, ctx=None, channel=None, user=None)[source]¶ Match if the response’s length is less than the specified length.
- Parameters
length (int) – The value to compare the response’s length with.
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
classmethod
less(value, ctx=None, channel=None, user=None)[source]¶ Match if the response is less than the specified value.
- Parameters
value (Union[int, float]) – The value to compare the response with.
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
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
collection (Sequence[str]) – The collection containing valid lowercase responses.
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
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
value (str) – The value to compare the response with.
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
classmethod
positive(ctx=None, channel=None, user=None)[source]¶ Match if the response is a positive number.
Assigns the response to
resultas afloat.- Parameters
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
classmethod
regex(pattern, ctx=None, channel=None, user=None)[source]¶ Match if the response matches the specified regex pattern.
This predicate will use
re.searchto find a match. The resultingmatch objectwill be assigned toresult.- Parameters
pattern (Union[
pattern object, str]) – The pattern to search for in the response.ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
classmethod
same_context(ctx=None, channel=None, user=None)[source]¶ Match if the message fits the described context.
- Parameters
ctx (Optional[Context]) – The current invocation context.
channel (Optional[discord.TextChannel]) – The channel we expect a message in. If unspecified, defaults to
ctx.channel. Ifctxis 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. Ifctxis unspecified too, the message’s author will be ignored.
- Returns
The event predicate.
- Return type
-
classmethod
valid_float(ctx=None, channel=None, user=None)[source]¶ Match if the response is a float.
Assigns the response to
resultas afloat.- Parameters
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
classmethod
valid_int(ctx=None, channel=None, user=None)[source]¶ Match if the response is an integer.
Assigns the response to
resultas anint.- Parameters
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
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.Memberobject toresult.This predicate cannot be used in DM.
- Parameters
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
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.Roleobject toresult.This predicate cannot be used in DM.
- Parameters
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
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.TextChannelobject toresult.This predicate cannot be used in DM.
- Parameters
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
classmethod
yes_or_no(ctx=None, channel=None, user=None)[source]¶ Match if the message is “yes”/”y” or “no”/”n”.
This will assign
Truefor yes, orFalsefor no to theresultattribute.- Parameters
ctx (Optional[Context]) – Same as
ctxinsame_context().channel (Optional[discord.TextChannel]) – Same as
channelinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
ReactionPredicate¶
-
class
redbot.core.utils.predicates.ReactionPredicate(predicate)[source]¶ Bases:
Callable[[discord.reaction.Reaction,discord.abc.User],bool]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 reaction 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: ClassVar[List[str]] = ['🇦', '🇧', '🇨', '🇩', '🇪', '🇫', '🇬', '🇭', '🇮', '🇯', '🇰', '🇱', '🇲', '🇳', '🇴', '🇵', '🇶', '🇷', '🇸', '🇹', '🇺', '🇻', '🇼', '🇽', '🇾', '🇿']¶ A list of all 26 alphabetical letter emojis.
- Type
List[str]
-
NUMBER_EMOJIS: ClassVar[List[str]] = ['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: ClassVar[Tuple[str, str]] = ('✅', '❎')¶ A tuple containing the tick emoji and cross emoji, in that order.
-
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
useris 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
-
classmethod
with_emojis(emojis, message=None, user=None)[source]¶ Match if the reaction is one of the specified emojis.
- Parameters
emojis (Sequence[Union[str, discord.Emoji, discord.PartialEmoji]]) – The emojis of which one we expect to be reacted.
message (discord.Message) – Same as
messageinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
classmethod
yes_or_no(message=None, user=None)[source]¶ Match if the reaction is a tick or cross emoji.
The emojis used are in
ReactionPredicate.YES_OR_NO_EMOJIS.This will assign
Truefor yes, orFalsefor no to theresultattribute.- Parameters
message (discord.Message) – Same as
messageinsame_context().user (Optional[discord.abc.User]) – Same as
userinsame_context().
- Returns
The event predicate.
- Return type
-
Mod Helpers¶
-
await
redbot.core.utils.mod.check_permissions(ctx, perms)[source]¶ Check if the author has required permissions.
This will always return
Trueif the author is a bot owner, or has theadministratorpermission. Ifpermsis empty, this will only check if the user is a bot owner.- Parameters
ctx (Context) – The command invocation 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.Permissionsclass.
- Returns
Trueif the author has the required permissions.- Return type
-
redbot.core.utils.mod.get_audit_reason(author, reason=None, *, shorten=False)[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.
shorten (bool) – When set to
True, the returned audit reason string will be shortened to fit the max length allowed by Discord audit logs.
- Returns
The formatted audit log reason.
- Return type
-
await
redbot.core.utils.mod.is_admin_or_superior(bot, obj)[source]¶ Same as
is_mod_or_superiorexcept 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
bot (redbot.core.bot.Red) – The bot object.
obj (
discord.Messageordiscord.Memberordiscord.Role) – The object to check permissions for.
- Returns
Trueif the object has admin permissions.- Return type
- Raises
TypeError – If the wrong type of
objwas 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
bot (redbot.core.bot.Red) – The bot object.
obj (
discord.Messageordiscord.Memberordiscord.Role) – The object to check permissions for.
- Returns
Trueif the object has mod permissions.- Return type
- Raises
TypeError – If the wrong type of
objwas 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
messages (
listofdiscord.Message) – The messages to bulk delete.channel (discord.TextChannel) – The channel to delete messages from.
- Raises
discord.Forbidden – You do not have proper permissions to delete the messages or you’re not using a bot account.
discord.HTTPException – Deleting the messages failed.
-
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 (
iterableofdiscord.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
Tunnel¶
-
class
redbot.core.utils.tunnel.Tunnel(*args, **kwargs)[source]¶ Bases:
objectA 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
-
origin¶ The channel in which it was opened
- Type
-
recipient¶ The user on the other end of the tunnel
- Type
-
await
close_because_disabled(close_message)[source]¶ Sends a mesage to both ends of the tunnel that the tunnel is now closed.
- Parameters
close_message (str) – The message to send to both ends of the tunnel.
-
await
communicate(*, message, topic=None, skip_message_content=False)[source]¶ Forwards a message.
- Parameters
message (
discord.Message) – The message to forwardtopic (
str) – A string to prependskip_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
- 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, *, use_cached=False, images_only=False)[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 fromuse_cached (
bool) – Whether to useproxy_urlrather thanurlwhen downloading the attachmentimages_only (
bool) – Whether only image attachments should be added to returned list
- Returns
A list of
discord.Fileobjects- Return type
list of
discord.File
-
staticmethod await
files_from_attatch(m, *, use_cached=False, images_only=False)¶ 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 fromuse_cached (
bool) – Whether to useproxy_urlrather thanurlwhen downloading the attachmentimages_only (
bool) – Whether only image attachments should be added to returned list
- Returns
A list of
discord.Fileobjects- 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
destination (discord.abc.Messageable) – Where to send
content (str) – The message content
embed (discord.Embed) – The embed to send
files (Optional[List[discord.File]]) – A list of files to send.
- Returns
The messages sent as a result.
- Return type
List[discord.Message]
- Raises
-
Common Filters¶
-
redbot.core.utils.common_filters.escape_spoilers(content)[source]¶ Get a string with spoiler syntax escaped.
-
redbot.core.utils.common_filters.escape_spoilers_and_mass_mentions(content)[source]¶ Get a string with spoiler syntax and mass mentions escaped
-
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, discord.com/invite, discord.me, or discord.io/discord.li invite URL.
-
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.
-
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://