Commands¶
- class twitchio.ext.commands.Command(callback: Callable[Concatenate[Component_T, Context, P], Coro] | Callable[Concatenate[Context, P], Coro], *, name: str, **kwargs: Unpack[CommandOptions])¶
The TwitchIO
commands.Command
class.These are usually not created manually, instead see:
- property component: Optional[Component_T]¶
Property returning the
Component
associated with this command orNone
if there is not one.
- property parent: Optional[Group[Component_T, P]]¶
Property returning the
Group
this sub-command belongs to orNone
if it is not apart of a group.
- property relative_name: str¶
Property returning the name of this command relative to it’s direct parent, if it has one.
E.g. Closely equivalent to
"{parent.name} {name}"
.If this command has no parent, this simply returns the name.
- property full_parent_name: str¶
Property returning the fully qualified name for all the parents for this command.
This takes into account the full parent hierarchy. If this command has no parents, this will be an empty
str
.E.g Closely equivalent to
"{first_parent.name} {second_parent.name}"
.
- property qualified_name: str¶
Property returning the fully qualified name for this command.
This takes into account the parent hierarchy. If this command has no parent, this simply returns the name.
E.g. Closely equivalent to
"{first_parent.name} {second_parent.name} {name}"
.This would be the string you would need to send minus the command prefix to invoke this command.
- property aliases: list[str]¶
Property returning a copy of the list of aliases associated with this command, if it has any set.
Could be an empty
list
if no aliases have been set.
- property extras: mappingproxy[Any, Any]¶
Property returning the extras stored on this command as
MappingProxyType
.Extras is a dict that can contain any information, and is stored on the command object for future retrieval.
- property has_error: bool¶
Property returning a
bool
, indicating whether this command has any local error handlers.
- property guards: list[collections.abc.Callable[..., bool] | collections.abc.Callable[..., collections.abc.Coroutine[Any, Any, bool]]]¶
Property returning a list of command specific
guard()
’s added.
- property callback: Callable[Concatenate[Component_T, Context, P], Coro] | Callable[Concatenate[Context, P], Coro]¶
Property returning the coroutine callback used in invocation. E.g. the function you wrap with
command()
.
- @ error(func: collections.abc.Callable[[twitchio.ext.commands.types_.Component_T, twitchio.ext.commands.core.CommandErrorPayload], collections.abc.Coroutine[Any, Any, None]] | collections.abc.Callable[[twitchio.ext.commands.core.CommandErrorPayload], collections.abc.Coroutine[Any, Any, None]]) collections.abc.Callable[[twitchio.ext.commands.types_.Component_T, twitchio.ext.commands.core.CommandErrorPayload], collections.abc.Coroutine[Any, Any, None]] | collections.abc.Callable[[twitchio.ext.commands.core.CommandErrorPayload], collections.abc.Coroutine[Any, Any, None]] ¶
This function is a decorator.
A decorator which adds a local error handler to this command.
Similar to
event_command_error()
except local to this command.
- @command
- @group
- defwalk_commands
- class twitchio.ext.commands.Group(*args: Any, **kwargs: Any)¶
The TwitchIO
commands.Command
class.These are usually not created manually, instead see:
- walk_commands() Generator[Union[Command[Component_T, P], Group[Component_T, P]]] ¶
A generator which recursively walks through the sub-commands and sub-groups of this group.
- @ command(name: str | None = None, aliases: list[str] | None = None, extras: dict[Any, Any] | None = None, **kwargs: Any) Any ¶
This function is a decorator.
A decorator which adds a
Command
as a sub-command to this group.See:
command
for more information on commandsExamples
# When added to a Bot or used in a component you can invoke this group and sub-commands with your prefix, E.g: # !socials # !socials discord OR !socials twitch # When invoke_fallback is True, the parent command will be invoked if a sub-command cannot be found... @commands.group(name="socials", invoke_fallback=True) async def socials_group(ctx: commands.Context) -> None: await ctx.send("https://discord.gg/RAKc3HF, https://twitch.tv/chillymosh, ...") @socials_group.command(name="discord", aliases=["disco"]) async def socials_discord(ctx: commands.Context) -> None: await ctx.send("https://discord.gg/RAKc3HF") @socials_group.command(name="twitch") async def socials_twitch(ctx: commands.Context) -> None: await ctx.send("https://twitch.tv/chillymosh")
- Parameters
name (str | None) – An optional custom name to use for this sub-command. If this is
None
or not passed, the coroutine function name will be used instead.aliases (list[str] | None) – An optional list of aliases to use for this command.
extras (dict) – A dict of any data which is stored on this command object. Can be used anywhere you have access to the command object, E.g. in a
before
orafter
hook.guards_after_parsing (bool) – An optional bool, indicating whether to run guards after argument parsing has completed. Defaults to
False
, which means guards will be checked before command arguments are parsed and available.cooldowns_before_guards (bool) – An optional bool, indicating whether to run cooldown guards after all other guards succeed. Defaults to
False
, which means cooldowns will be checked after all guards have successfully completed.bypass_global_guards (bool) – An optional bool, indicating whether the command should bypass the
global_guard()
. Defaults toFalse
.
- @ group(name: str | None = None, aliases: list[str] | None = None, extras: dict[Any, Any] | None = None, **kwargs: Any) Any ¶
This function is a decorator.
A decorator which adds a
Group
as a sub-group to this group.Examples
# When added to a Bot or used in a component you can invoke this group and sub-commands with your prefix, E.g: # !socials # !socials discord OR !socials twitch # !socials discord one OR !socials discord two # When invoke_fallback is True, the parent command will be invoked if a sub-command cannot be found... @commands.group(name="socials", invoke_fallback=True) async def socials_group(ctx: commands.Context) -> None: await ctx.send("https://discord.gg/RAKc3HF, https://twitch.tv/chillymosh, ...") @socials_group.command(name="twitch") async def socials_twitch(ctx: commands.Context) -> None: await ctx.send("https://twitch.tv/chillymosh") # Add a group to our parent group which further separates the commands... @socials_group.group(name="discord", aliases=["disco"], invoke_fallback=True) async def socials_discord(ctx: commands.Context) -> None: await ctx.send("https://discord.gg/RAKc3HF, https://discord.gg/...") @socials_discord.command(name="one", aliases=["1"]) async def socials_discord_one(ctx: commands.Context) -> None: await ctx.send("https://discord.gg/RAKc3HF") @socials_discord.command(name="two", aliases=["2"]) async def socials_discord_two(ctx: commands.Context) -> None: await ctx.send("https://discord.gg/...")
- Parameters
name (str | None) – An optional custom name to use for this group. If this is
None
or not passed, the coroutine function name will be used instead.aliases (list[str] | None) – An optional list of aliases to use for this group.
extras (dict) – A dict of any data which is stored on this command object. Can be used anywhere you have access to the command object, E.g. in a
before
orafter
hook.invoke_fallback (bool) – An optional bool which tells the parent to be invoked as a fallback when no sub-command can be found. Defaults to
False
.apply_cooldowns (bool) – An optional bool indicating whether the cooldowns on this group are checked before invoking any sub commands. Defaults to
True
.apply_guards (bool) – An optional bool indicating whether the guards on this group should be ran before invoking any sub commands. Defaults to
True
.
- asyncclear_messages
- asyncdelete_message
- asyncinvoke
- defis_owner
- defis_valid
- asyncreply
- asyncsend
- asyncsend_announcement
- class twitchio.ext.commands.Context(message: ChatMessage, *, bot: Bot)¶
The Context class constructed when a message is received and processed via the
event_message()
event in aBot
.This object is available in all
Command
’s,Groups
’s and associated sub-commands and all command related events. It is also included in various areas relating to command invocation, including, Guards and Before and After Hooks.The Context class is a useful tool which provides information surrounding the command invocation, the broadcaster and chatter involved and provides many useful methods and properties for ease of us.
Usually you wouldn’t construct this class this yourself, however it could be subclassed to implement custom functionality or constructed from a message received via EventSub in
event_message()
.- Parameters
message (
twitchio.ChatMessage
) – The message object, usually received viaevent_message()
.bot (
Bot
) – YourBot
class, this is required to perform multiple operations.
- property message: ChatMessage¶
Proptery of the message object that this context is built from. This is the
ChatMessage
received via EventSub from the chatter.
- property component: Component | None¶
Property returning the
Component
that this context was used in, if theCommand
belongs to it. This is only set once aCommand
has been found and invoked.
- property command: Command[Any, ...] | None¶
Property returning the
Command
associated with this context, if found.This is only set when a command begins invocation. Could be
None
if the command has not started invocation, or one was not found.
- property invoked_subcommand: Command[Any, ...] | None¶
Property returning the subcommand associated with this context if their is one.
Returns
None
when a standard command without a parentGroup
is invoked.
- property invoked_with: str | None¶
Property returning the string the context used to attempt to find a valid
Command
.Could be
None
if a command has not been invoked from this context yet.
- property chatter: Chatter¶
Property returning the
twitchio.PartialUser
who sent theChatMessage
in the channel that this context is built from.
- property broadcaster: PartialUser¶
Property returning the
twitchio.PartialUser
who is the broadcaster of the channel associated with this context.
- property source_broadcaster: PartialUser | None¶
Property returning the
twitchio.PartialUser
who is the broadcaster of the channel associated with the originalChatMessage
. This will usually always beNone
as the default behaviour is to ignore shared messages when invoking commands.
- property channel: PartialUser¶
An alias to
broadcaster
.
- property prefix: str | None¶
Property returning the prefix associated with this context or
None
.This will only return a prefix after the context has been prepared, which occurs during invocation of a command, and after a valid prefix found.
- property content: str¶
Property returning the raw content of the message associated with this context.
- property args: list[Any]¶
A list of arguments processed and passed to the
Command
callback.This is only set after the command begins invocation.
- property kwargs: dict[str, Any]¶
A dict of keyword-arguments processed and passed to the
Command
callback.This is only set after the command begins invocation.
- property failed: bool¶
Property indicating whether the context failed to invoke the associated command.
- is_owner() bool ¶
Method which returns whether the chatter associated with this context is the owner of the bot.
Warning
You must have set the
owner_id
correctly first, otherwise this method will returnFalse
.- Returns
Whether the chatter that this context is associated with is the owner of this bot.
- Return type
- is_valid() bool ¶
Method which indicates whether this context is valid. E.g. hasa valid command prefix.
- async invoke() bool | None ¶
This function is a coroutine.
Invoke and process the command associated with this message context if it is valid.
This method first prepares the context for invocation, and checks whether the context has a valid command with a valid prefix.
Warning
Usually you wouldn’t use this method yourself, as it handled by TwitchIO interanally when
process_commands()
is called in atwitchio.event_message()
event.Important
Due to the way this method works, the only error raised will be
CommandNotFound
. All other errors that occur will be sent to thetwitchio.event_command_error()
event.- Returns
bool – If this method explicitly returns
False
the context is not valid. E.g. has no valid command prefix. WhenTrue
the command successfully completed invocation without error.None
– Returned when the command is found and begins to process. This does not indicate the command was completed successfully. See alsotwitchio.event_command_completed()
for an event fired when a command successfully completes the invocation process.
- Raises
CommandNotFound – The
Command
trying to be invoked could not be found.
- async send(content: str, *, me: bool = False) SentMessage ¶
This function is a coroutine.
Send a chat message to the channel associated with this context.
Important
You must have the
user:write:chat
scope. If an app access token is used, then additionally requires theuser:bot
scope on the bot, and eitherchannel:bot
scope from the broadcaster or moderator status.See: … for more information.
- Parameters
content (str) – The content of the message you would like to send. This cannot exceed
500
characters. Additionally the content parameter will be stripped of all leading and trailing whitespace.me (bool) – An optional bool indicating whether you would like to send this message with the
/me
chat command.
- Returns
The payload received by Twitch after sending this message.
- Return type
- Raises
HTTPException – Twitch failed to process the message, could be
400
,401
,403
,422
or any5xx
status code.MessageRejectedError – Twitch rejected the message from various checks.
- async reply(content: str, *, me: bool = False) SentMessage ¶
This function is a coroutine.
Send a chat message as a reply to the user who this message is associated with and to the channel associated with this context.
Important
You must have the
user:write:chat
scope. If an app access token is used, then additionally requires theuser:bot
scope on the bot, and eitherchannel:bot
scope from the broadcaster or moderator status.See: … for more information.
- Parameters
content (str) – The content of the message you would like to send. This cannot exceed
500
characters. Additionally the content parameter will be stripped of all leading and trailing whitespace.me (bool) – An optional bool indicating whether you would like to send this message with the
/me
chat command.
- Returns
The payload received by Twitch after sending this message.
- Return type
- Raises
HTTPException – Twitch failed to process the message, could be
400
,401
,403
,422
or any5xx
status code.MessageRejectedError – Twitch rejected the message from various checks.
- async send_announcement(content: str, *, color: Optional[Literal['blue', 'green', 'orange', 'purple', 'primary']] = None) None ¶
This function is a coroutine.
Send an announcement to the channel associated with this channel as the bot.
Important
The broadcaster of the associated channel must have granted your bot the
moderator:manage:announcements
scope. See: … for more information.- Parameters
content (str) – The content of the announcement to send. This cannot exceed 500 characters. Announcements longer than
500
characters will be truncated instead by Twitch.color (Literal["blue", "green", "orange", "purple", "primary"] | None) – An optional colour to use for the announcement. If set to
"primary
” orNone
the channels accent colour will be used instead. Defaults toNone
.
- Return type
None
- Raises
HTTPException – Sending the announcement failed. Could be
400
,401
or any5xx
status code.
- async delete_message() None ¶
This function is a coroutine.
Delete the message associated with this context.
Important
The broadcaster of the associated channel must have granted your bot the
moderator:manage:chat_messages
scope. See: … for more information.Note
You cannot delete messages from the broadcaster or any moderator, and the message must not be more than
6 hours
old.- Raises
HTTPException – Twitch failed to remove the message. Could be
400
,401
,403
,404
or any5xx
status code.
- async clear_messages() None ¶
This function is a coroutine.
Clear all the chat messages from chat for the channel associated with this context.
Important
The broadcaster of the associated channel must have granted your bot the
moderator:manage:chat_messages
scope. See: … for more information.- Raises
HTTPException – Twitch failed to remove the message. Could be
400
,401
,403
,404
or any5xx
status code.
Decorators¶
- @ twitchio.ext.commands.command(name: str | None = None, aliases: list[str] | None = None, extras: dict[Any, Any] | None = None, **kwargs: Any) Any ¶
This function is a decorator.
A decorator which turns a coroutine into a
Command
which can be used inComponent
’s or added to aBot
.Commands are powerful tools which enable bots to process messages and convert the content into mangeable arguments and
Context
which is parsed to the wrapped callback coroutine.Commands also benefit to such things as
guard()
’s and thebefore
andafter
hooks on both,Component
andBot
.Command callbacks should take in at minimum one parameter, which is
Context
and is always passed.- Parameters
name (str | None) – An optional custom name to use for this command. If this is
None
or not passed, the coroutine function name will be used instead.aliases (list[str] | None) – An optional list of aliases to use for this command.
extras (dict) – A dict of any data which is stored on this command object. Can be used anywhere you have access to the command object, E.g. in a
before
orafter
hook.guards_after_parsing (bool) – An optional bool, indicating whether to run guards after argument parsing has completed. Defaults to
False
, which means guards will be checked before command arguments are parsed and available.cooldowns_before_guards (bool) – An optional bool, indicating whether to run cooldown guards after all other guards succeed. Defaults to
False
, which means cooldowns will be checked after all guards have successfully completed.bypass_global_guards (bool) – An optional bool, indicating whether the command should bypass the
Bot.global_guard()
. Defaults toFalse
.
Examples
# When added to a Bot or used in a component you can invoke this command with your prefix, E.g: # !hi or !howdy @commands.command(name="hi", aliases=["hello", "howdy"]) async def hi_command(ctx: commands.Context) -> None: ...
- Raises
ValueError – The callback being wrapped is already a command.
TypeError – The callback must be a coroutine function.
- @ twitchio.ext.commands.group(name: str | None = None, aliases: list[str] | None = None, extras: dict[Any, Any] | None = None, **kwargs: Any) Any ¶
This function is a decorator.
A decorator which turns a coroutine into a
Group
which can be used inComponent
’s or added to aBot
.Group commands act as parents to other commands (sub-commands).
See:
command()
for more information on commands.Group commands are a powerful way of grouping similar sub-commands into a more user friendly interface.
Group callbacks should take in at minimum one parameter, which is
Context
and is always passed.- Parameters
name (str | None) – An optional custom name to use for this group. If this is
None
or not passed, the coroutine function name will be used instead.aliases (list[str] | None) – An optional list of aliases to use for this group.
extras (dict) – A dict of any data which is stored on this command object. Can be used anywhere you have access to the command object, E.g. in a
before
orafter
hook.invoke_fallback (bool) – An optional bool which tells the parent to be invoked as a fallback when no sub-command can be found. Defaults to
False
.apply_cooldowns (bool) – An optional bool indicating whether the cooldowns on this group are checked before invoking any sub commands. Defaults to
True
.apply_guards (bool) – An optional bool indicating whether the guards on this group should be ran before invoking any sub commands. Defaults to
True
.
Examples
# When added to a Bot or used in a component you can invoke this group and sub-commands with your prefix, E.g: # !socials # !socials discord OR !socials twitch # When invoke_fallback is True, the parent command will be invoked if a sub-command cannot be found... @commands.group(name="socials", invoke_fallback=True) async def socials_group(ctx: commands.Context) -> None: await ctx.send("https://discord.gg/RAKc3HF, https://twitch.tv/chillymosh, ...") @socials_group.command(name="discord", aliases=["disco"]) async def socials_discord(ctx: commands.Context) -> None: await ctx.send("https://discord.gg/RAKc3HF") @socials_group.command(name="twitch") async def socials_twitch(ctx: commands.Context) -> None: await ctx.send("https://twitch.tv/chillymosh")
- Raises
ValueError – The callback being wrapped is already a command or group.
TypeError – The callback must be a coroutine function.
- @ twitchio.ext.commands.cooldown(*, base: BaseCooldown, rate: int, per: float, key: Callable[[Any], Hashable] | Callable[[Any], Coroutine[Any, Any, Hashable]] | BucketType, **kwargs: Any)¶
This function is a decorator.
A decorator which adds a
Cooldown
to aCommand
.The parameters of this decorator may change depending on the class passed to the
base
parameter. The parameters needed for the default built-in classes are listed instead.When a command is on cooldown or ratelimited, the
CommandOnCooldown
exception is raised and propagated to all error handlers.- Parameters
base (
BaseCooldown
) –Optional base class to use to construct the cooldown. By default this is the
Cooldown
class, which implements aToken Bucket Algorithm
. Another option is theGCRACooldown
class which implements the Generic Cell Rate Algorithm, which can be thought of as similar to a continuous state leaky-bucket algorithm, but instead of updating internal state, calculates a Theoretical Arrival Time (TAT), making it more performant, and dissallowing short bursts of requests. However before choosing a class, consider reading more information on the differences between theToken Bucket
andGCRA
.A custom class which inherits from
BaseCooldown
could also be used. Allkeyword-arguments
passed to this decorator, minusbase
andkey
will also be passed to the constructor of the cooldown base class.Useful if you would like to implement your own ratelimiting algorithm.
key (Callable[[Any], Hashable] | Callable[[Any], Coroutine[Any, Any, Hashable]] |
BucketType
) –A regular or coroutine function, or
BucketType
which must return atyping.Hashable
used to determine the keys for the cooldown.The
BucketType
implements some default strategies. If your function returnsNone
the cooldown will be bypassed. See below for some examples. By default the key ischatter
.rate (int) – An
int
indicating how many times a command should be allowedper
x amount of time. Note the relevance and effects of bothrate
andper
change slightly between algorithms.per (float | datetime.timedelta) –
A
float
ordatetime.timedelta
indicating the length of the time (as seconds) a cooldown window is open.E.g. if
rate
is2
andper
is60.0
, using the defaultCooldown
class, you will only be able to sendtwo
commandsper 60 seconds
, with the window starting when you send the first command.
Examples
Using the default
Cooldown
to allow the command to be ran twice by an individual chatter, every 10 seconds.@commands.command() @commands.cooldown(rate=2, per=10, key=commands.BucketType.chatter) async def hello(ctx: commands.Context) -> None: ...
Using a custom key to bypass cooldowns for certain users.
def bypass_cool(ctx: commands.Context) -> typing.Hashable | None: # Returning None will bypass the cooldown if ctx.chatter.name.startswith("cool"): return None # For everyone else, return and call the default chatter strategy # This strategy returns a tuple of (channel/broadcaster.id, chatter.id) to use as the unique key return commands.BucketType.chatter(ctx) @commands.command() @commands.cooldown(rate=2, per=10, key=bypass_cool) async def hello(ctx: commands.Context) -> None: ...
Using a custom function to implement dynamic keys.
async def custom_key(ctx: commands.Context) -> typing.Hashable | None: # As an example, get some user info from a database with the chatter... # This is just to showcase a use for an async version of a custom key... ... # Example column in database... if row["should_bypass_cooldown"]: return None # Note: Returing chatter.id is equivalent to commands.BucketType.user NOT commands.BucketType.chatter # which uses the channel ID and User ID together as the key... return ctx.chatter.id @commands.command() @commands.cooldown(rate=1, per=300, key=custom_key) async def hello(ctx: commands.Context) -> None: ...
Guards¶
- twitchio.ext.commands.guard(predicate: collections.abc.Callable[[...], bool] | collections.abc.Callable[[...], collections.abc.Coroutine[Any, Any, bool]]) Any ¶
A function which takes in a predicate as a either a standard function or coroutine function which should return either
True
orFalse
, and adds it to yourCommand
as a guard.The predicate function should take in one parameter,
commands.Context
, the context used in command invocation.If the predicate function returns
False
, the chatter will not be able to invoke the command and an error will be raised. If the predicate function returnsTrue
the chatter will be able to invoke the command, assuming all the other guards also pass their predicate checks.Guards can also raise custom exceptions, however your exception should inherit from
GuardFailure
which will allow your exception to propagate successfully to error handlers.Any number of guards can be used on a
Command
and all must pass for the command to be successfully invoked.All guards are executed in the specific order displayed below:
Global Guard:
commands.Bot.global_guard()
Component Guards:
commands.Component.guard()
Command Specific Guards: The command specific guards, E.g. by using this or other guard decorators on a command.
Note
Guards are checked and ran after all command arguments have been parsed and converted, but before any
before_invoke
hooks are ran.It is easy to create simple decorator guards for your commands, see the examples below.
Some built-in helper guards have been premade, and are listed below:
Example
def is_cool(): def predicate(ctx: commands.Context) -> bool: return ctx.chatter.name.startswith("cool") return commands.guard(predicate) @is_cool() @commands.command() async def cool(self, ctx: commands.Context) -> None: await ctx.reply("You are cool...!")
- Raises
GuardFailure – The guard predicate returned
False
and prevented the chatter from using the command.
- @ twitchio.ext.commands.is_owner() Any ¶
This function is a decorator.
A decorator which adds a
guard()
to aCommand
.This guards adds a predicate which prevents any chatter from using a command who does is not the owner of this bot. You can set the owner of the bot via
owner_id
.- Raises
GuardFailure – The guard predicate returned
False
and prevented the chatter from using the command.
- @ twitchio.ext.commands.is_staff() Any ¶
This function is a decorator.
A decorator which adds a
guard()
to aCommand
.This guards adds a predicate which prevents any chatter from using a command who does not possess the
Twitch Staff
badge.- Raises
GuardFailure – The guard predicate returned
False
and prevented the chatter from using the command.
- @ twitchio.ext.commands.is_broadcaster() Any ¶
This function is a decorator.
A decorator which adds a
guard()
to aCommand
.This guards adds a predicate which prevents any chatter from using a command who does not possess the
Broadcaster
badge.See also,
is_elevated()
for a guard to allow thebroadcaster
, anymoderator
orVIP
chatter to use the command.- Raises
GuardFailure – The guard predicate returned
False
and prevented the chatter from using the command.
- @ twitchio.ext.commands.is_moderator() Any ¶
This function is a decorator.
A decorator which adds a
guard()
to aCommand
.This guards adds a predicate which prevents any chatter from using a command who does not possess the
Moderator
badge.See also,
is_elevated()
for a guard to allow thebroadcaster
, anymoderator
orVIP
chatter to use the command.- Raises
GuardFailure – The guard predicate returned
False
and prevented the chatter from using the command.
- @ twitchio.ext.commands.is_vip() Any ¶
This function is a decorator.
A decorator which adds a
guard()
to aCommand
.This guards adds a predicate which prevents any chatter from using a command who does not possess the
VIP
badge.Note
Due to a Twitch limitation, moderators and broadcasters can not be VIPs, another guard has been made to help aid in allowing these members to also be seen as VIP, see:
is_elevated()
.- Raises
GuardFailure – The guard predicate returned
False
and prevented the chatter from using the command.
- @ twitchio.ext.commands.is_elevated() Any ¶
This function is a decorator.
A decorator which adds a
guard()
to aCommand
.This guards adds a predicate which prevents any chatter from using a command who does not posses one or more of the folowing badges:
broadcaster
,moderator
orVIP
.Important
The chatter only needs 1 of the badges to pass the guard.
Example
# This command can be run by anyone with broadcaster, moderator OR VIP status... @commands.is_elevated() @commands.command() async def test(self, ctx: commands.Context) -> None: await ctx.reply("You are allowed to use this command!")
- Raises
GuardFailure – The guard predicate returned
False
and prevented the chatter from using the command.
Cooldowns¶
- class twitchio.ext.commands.BaseCooldown¶
Base class used to implement your own cooldown algorithm for use with
cooldown()
.Some built-in cooldown algorithms already exist:
Cooldown
- (Token Bucket Algorithm
)GCRACooldown
- (Generic Cell Rate Algorithm
)
Note
Every base method must be implemented in this base class.
- abstract update(*args: Any, **kwargs: Any) float | None ¶
Base method which should be implemented to update the cooldown/ratelimit.
This is where your algorithm logic should be contained.
Important
This method should always return a
float
orNone
. IfNone
is returned by this method, the cooldown will be considered bypassed.- Returns
float
– The time needed to wait before you are off cooldown.None
– Bypasses the cooldown.
- abstract copy() Self ¶
Base method which should be implemented to return a copy of this class in it’s original state.
- class twitchio.ext.commands.Cooldown(*, rate: int, per: float | datetime.timedelta)¶
Default cooldown algorithm for
cooldown()
, which implements aToken Bucket Algorithm
.See:
cooldown()
for more documentation.
- class twitchio.ext.commands.GCRACooldown(*, rate: int, per: float | datetime.timedelta)¶
GCRA cooldown algorithm for
cooldown()
, which implements theGCRA
ratelimiting algorithm.See:
cooldown()
for more documentation.
- class twitchio.ext.commands.BucketType¶
Enum representing default implementations for the key argument in
cooldown()
.- default¶
The cooldown will be considered a global cooldown shared across every channel and user.
- user¶
The cooldown will apply per user, accross all channels.
- channel¶
The cooldown will apply to every user/chatter in the channel.
- chatter¶
The cooldown will apply per user, per channel.