Commands Ext#

Walkthrough#

The commands ext is meant purely for creating twitch chatbots. It gives you powerful tools, including dynamic loading/unloading/reloading of modules, organization of code using Cogs, and of course, commands.

The base of this ext revolves around the Bot. Bot is a subclass of Client, which means it has all the functionality of Client, while also adding on the features needed for command handling.

Note

Because Bot is a subclass of Client, you do not need to use Client at all. All of the functionality you’re looking for is contained within Bot. The only exception for this rule is when using the Eventsub Ext.

To set up your bot for commands, the first thing we’ll do is create a Bot.

from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!")

bot.run()

Bot has two required arguments, token and prefix. token is the same as for Client, and prefix is a new argument, specific to commands. You can pass many different things as a prefix, for example:

import twitchio
from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!")

bot = commands.Bot(token="...", prefix=("!", "?"))

def prefix_callback(bot: commands.Bot, message: twitchio.Message) -> str:
    if message.channel.name == "iamtomahawkx":
        return "!"
    elif message.channel.name == "chillymosh":
        return "?"
    else:
        return ">>"

bot = commands.Bot(token="...", prefix=prefix_callback)

bot.run()

All of those methods are valid prefixes, you can even pass an async function if needed. For this demo, we’ll stick to using !. We’ll also be passing 3 initial channels to our bot, so that we can send commands right away on them:

from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

bot.run()

___

To create a command, we’ll use the following code:

async def cookie(ctx: commands.Context) -> None:
    await ctx.send(f"{ctx.author.name} gets a cookie!")

Every command takes a ctx argument, which gives you information on the command, who called it, from what channel, etc. You can read more about the ctx argument Here.

Once we’ve made our function, we can tie it into our bot like this:

from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

@bot.command()
async def cookie(ctx: commands.Context) -> None:
    await ctx.send(f"{ctx.author.name} gets a cookie!")

bot.run()

And then we can use it like this:

../_images/commands_basic_1.png

We’ve made use of a decorator here to make the cookie function a command that will be called whenever someone types !cookie in one of our twitch channels. But sometimes we’ll want our function to be named something different than our command, or we’ll want aliases so that multiple things trigger our command. We can do that by passing arguments to the decorator, like so:

from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

@bot.command(name="cookie", aliases=("cookies", "biscuits"))
async def cookie_command(ctx: commands.Context) -> None:
    await ctx.send(f"{ctx.author.name} gets a cookie!")

bot.run()

Now our command can be triggered with any of !cookie, !cookies, or !biscuits. But it cannot be triggered with !cookie_command:

../_images/commands_basic_2.png

You may notice that if you try to run !cookie_command, you get an error in your console about the command not being found. Don’t worry, we’ll hide that later, when we cover error handling.

___

Now let’s say we want to take an argument for our command. We want to specify how many cookies the bot will give out. Fortunately, twitchio has that functionality built right in! We can simply add an argument to our function, and the argument will be added.

from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

@bot.command(name="cookie", aliases=("cookies", "biscuits"))
async def cookie_command(ctx: commands.Context, amount) -> None:
    await ctx.send(f"{ctx.author.name} gets {amount} cookie(s)!")

bot.run()
../_images/commands_arguments_1.png

Now, you’ll notice that I passed words? as the argument in the image, and the code handled it fine. While it’s good that it didn’t error, we actually want it to error here, as our code should only take numbers! Good news, twitchio’s argument handling goes beyond simple positional arguments. We can use python’s typehints to tell the parser to only accept integers:

from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

@bot.command(name="cookie", aliases=("cookies", "biscuits"))
async def cookie_command(ctx: commands.Context, amount: int) -> None:
    await ctx.send(f"{ctx.author.name} gets {amount} cookie(s)!")

bot.run()
../_images/commands_arguments_2.png

Good, the command didn’t accept the word where the number should be. We’ve got a messy error in our console, that looks like this:

twitchio.ext.commands.errors.ArgumentParsingFailed: Invalid argument parsed at `amount` in command `cookie`. Expected type <class 'int'> got <class 'str'>.

but we’ll clean that up when we cover error handling.

Twitchio allows for many kinds of typehints to be used, including built in types like str (the default), int, and bool. It also allows for some Twitchio models to be hinted. For instance, you can grab another user like this:

import twitchio
from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

@bot.command(name="cookie", aliases=("cookies", "biscuits"))
async def cookie_command(ctx: commands.Context, amount: int, user: twitchio.User) -> None:
    await ctx.send(f"{user.name} gets {amount} cookie(s)!")

bot.run()
../_images/commands_arguments_3.png

Note that an error is raised for the last message, because “anfkednfowinoi” does not exist.

twitchio.ext.commands.errors.BadArgument: User 'anfkednfowinoi' was not found.

The built in models that you can use include:

Note

The User / PartialUser converters do make an API call, so they should only be used in cases where you need to ensure the user exists (as an error will be raised when they don’t exist). For most usages of finding another user, you can simply use str or twitchio.PartialChatter.

Because of this downside, we’ll be using PartialChatter for the remainder of this walkthrough.

___

Now, let’s say we want to have the option to pass a chatter, but we want it to be optional. If a chatter isn’t passed, we use the author instead. We can accomplish this through the use of Python’s typing module:

import twitchio
from typing import Optional
from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

@bot.command(name="cookie", aliases=("cookies", "biscuits"))
async def cookie_command(ctx: commands.Context, amount: int, user: Optional[twitchio.PartialChatter]) -> None:
    if user is None:
        user = ctx.author

    await ctx.send(f"{user.name} gets {amount} cookie(s)!")

bot.run()

If you’re on Python 3.10+, you could also structure it like this:

import twitchio
from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

@bot.command(name="cookie", aliases=("cookies", "biscuits"))
async def cookie_command(ctx: commands.Context, amount: int, user: twitchio.PartialChatter | None) -> None:
    if user is None:
        user = ctx.author

    await ctx.send(f"{user.name} gets {amount} cookie(s)!")

bot.run()
../_images/commands_arguments_4.png

With that 3.10 syntax in mind, we could also replace that None for another type. Maybe we want a clip, or any URL. We could accomplish this using the Union syntax (as it’s known). We’ll make use of yarl here to parse URLs.

Note

If you’re using anything below 3.10, you can use typing.Union as a substitute for that syntax, like so:

from typing import Union

def foo(argument: Union[str, int]) -> None:
    ...

At the same time, we’ll introduce custom converters. While the library handles basic types and certain twitch types for you, you may wish to make your own converters at some point. The library allows you to do this by passing a callable function to the typehint. Additionally, you can use typing.Annotated to transform the argument for the type checker. This feature was introduced in Python 3.9, if you wish to use this feature on lower versions consider installing typing_extensions to use it from there. Using Annotated is not required, however it will help your type checker distinguish between converters and types.

Lets take a look at custom converters and Annotated:

import yarl
import twitchio
from typing import Annotated
from twitchio.ext import commands

def url_converter(ctx: commands.Context, arg: str) -> yarl.URL:
    return yarl.URL(arg) # this will raise if its an invalid URL.

@bot.command(name="share")
async def share_command(ctx: commands.Context, url: Annotated[yarl.URL, url_converter]) -> None:
    await ctx.send(f"{ctx.author.name} wants to share a link on {url.host}: {url}")

Now that we’ve seen how custom converters work, let’s combine them with the Union syntax to create a command that will take either a Clip or a URL. I’ve spread the command definition out over multiple lines to make it more readable.

import yarl
import twitchio
from typing import Annotated
from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

def url_converter(ctx: commands.Context, arg: str) -> yarl.URL:
    return yarl.URL(arg) # this will raise if its an invalid URL.

@bot.command(name="share")
async def share_command(
    ctx: commands.Context,
    url: twitchio.Clip | Annotated[yarl.URL, url_converter]
) -> None:
    if isinstance(url, twitchio.Clip):
        await ctx.send(f"{ctx.author.name} wants to share a clip from {url.broadcaster.name}: {url.url}")
    else:
        await ctx.send(f"{ctx.author.name} wants to share a link on {url.host}: {url}")

bot.run()
../_images/commands_arguments_5.png

___

Let’s take a look at the different ways you can pass strings to your commands. We’ll use this example code:

import twitchio
from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

@bot.command(name="echo")
async def echo(ctx: commands.Context, phrase: str, other_phrase: str | None) -> None:
    response = f"Echo! {phrase}"
    if other_phrase:
        response += f". You also said: {other_phrase}"

    await ctx.send(response)

bot.run()

At it’s most basic, we can simply pass a word, and get a word back:

../_images/commands_parsing_1.png

However what do we do when we want to pass a sentence or multiple words to one argument? If change nothing here, and add a second word, we’ll get some unwanted behaviour:

../_images/commands_parsing_2.png

However, there are two workarounds we can do.

First, we can tell our users to quote their argument:

../_images/commands_parsing_3.png

However, if we want to work around it on the bot side, we can change our code to use a special positional only argument. In python, positional only arguments are ones that you must specify explicitly when calling the function. However, twitchio interprets them to mean “pass me the rest of the input”. This means that you can only have one of these arguments. This must also be the last argument, because it consumes the rest of the input.

Let’s see how this would look:

import twitchio
from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

@bot.command(name="echo")
async def echo(ctx: commands.Context, *, phrase: str) -> None:
    response = f"Echo! {phrase}"

    await ctx.send(response)

bot.run()

And how it turns out:

../_images/commands_parsing_4.png

___

Now, let’s clean up our errors a bit. To do this, we’ll take a mix of the code examples from above:

import yarl
import twitchio
from typing import Annotated
from twitchio.ext import commands

bot = commands.Bot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

def youtube_converter(ctx: commands.Context, arg: str) -> yarl.URL:
    url = yarl.URL(arg) # this will raise if its an invalid URL.
    if url.host not in ("youtube.com", "youtu.be"):
        raise RuntimeError("Not a youtube link!")

    return url

@bot.command(name="share")
async def share_command(
    ctx: commands.Context,
    url: Annotated[yarl.URL, youtube_converter],
    hype: int,
    *,
    comment: str
) -> None:
    hype_level = "hype" if 0 < hype < 5 else "very hype"
    await ctx.send(f"{ctx.author.name} wants to share a {hype_level} link on {url.host}: {comment}")

bot.run()

Currently, any errors that are raised will simply go directly into our console, but that’s not really ideal behaviour. We want to choose errors to ignore, errors to print, and errors to send to the user. We can do this by subclassing our Bot, and overriding the command_error event. Let’s take a look at that specifically:

from twitchio.ext import commands

class MyBot(commands.Bot):
    async def event_command_error(self, context: commands.Context, error: Exception):
        print(error)

bot = MyBot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

# SNIP: command

bot.run()

Great, we’ve switched from the default behaviour to a custom behaviour. However, we can improve on it.

There are a couple errors that you are garaunteed to encounter. CommandNotFound is probably the most annoying one, so let’s start there:

class MyBot(commands.Bot):
    async def event_command_error(self, context: commands.Context, error: Exception):
        if isinstance(error, commands.CommandNotFound):
            return

        print(error)

# SNIP: everything else

Now we will no longer see that pesky command not found error in our console every time someone mistypes a command. Next, we can handle some of the errors we saw earlier, like ArgumentParsingFailed:

class MyBot(commands.Bot):
    async def event_command_error(self, context: commands.Context, error: Exception):
        if isinstance(error, commands.CommandNotFound):
            return

        elif isinstance(error, commands.ArgumentParsingFailed):
            await context.send(error.message)

        else:
            print(error)

# SNIP: everything else

Now we send argument parsing errors directly to the user, so they can adjust their input. Let’s try combining this subclass with our existing code:

import yarl
import twitchio
from typing import Annotated
from twitchio.ext import commands

class MyBot(commands.Bot):
    async def event_command_error(self, context: commands.Context, error: Exception):
        if isinstance(error, commands.CommandNotFound):
            return

        elif isinstance(error, commands.ArgumentParsingFailed):
            await context.send(error.message)

        else:
            print(error)

bot = MyBot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

def youtube_converter(ctx: commands.Context, arg: str) -> yarl.URL:
    url = yarl.URL(arg) # this will raise if its an invalid URL.
    if url.host not in ("youtube.com", "youtu.be"):
        raise RuntimeError("Not a youtube link!")

    return url

@bot.command(name="share")
async def share_command(
    ctx: commands.Context,
    url: Annotated[yarl.URL, youtube_converter],
    hype: int,
    *,
    comment: str
) -> None:
    hype_level = "hype" if 0 < hype < 5 else "very hype"
    await ctx.send(f"{ctx.author.name} wants to share a {hype_level} link on {url.host}: {comment}")

bot.run()

Now, let’s pass it some bad arguments and see what happens.

../_images/commands_errors_1.png

Now, that isn’t very user intuitive, but for the purpose of this walkthrough, it’ll do just fine. You can tweak that as you want! Let’s fill this out with some more common errors:

class MyBot(commands.Bot):
    async def event_command_error(self, context: commands.Context, error: Exception):
        if isinstance(error, commands.CommandNotFound):
            return

        elif isinstance(error, commands.ArgumentParsingFailed):
            await context.send(error.message)

        elif isinstance(error, commands.MissingRequiredArgument):
            await context.send("You're missing an argument: " + error.name)

        elif isinstance(error, commands.CheckFailure): # we'll explain checks later, but lets include it for now.
            await context.send("Sorry, you cant run that command: " + error.args[0])

        else:
            print(error)

Now when we run our code we get some actual errors in our chat!

../_images/commands_errors_2.png

To create your own errors to handle here from arguments, subclass BadArgument and raise that custom exception in your argument parser. If you want to raise errors from your commands, subclass TwitchCommandError instead. As an example, let’s change the youtube converter to use a custom error:

import yarl
import twitchio
from typing import Annotated
from twitchio.ext import commands

class MyBot(commands.Bot):
    async def event_command_error(self, context: commands.Context, error: Exception):
        if isinstance(error, commands.CommandNotFound):
            return

        elif isinstance(error, commands.ArgumentParsingFailed):
            await context.send(error.message)

        elif isinstance(error, commands.MissingRequiredArgument):
            await context.send("You're missing an argument: " + error.name)

        elif isinstance(error, commands.CheckFailure): # we'll explain checks later, but lets include it for now.
            await context.send("Sorry, you cant run that command: " + error.args[0])

        elif isinstance(error, YoutubeConverterError):
            await context.send(f"{error.link} is not a valid youtube URL!")

        else:
            print(error)

bot = MyBot(token="...", prefix="!", initial_channels=["iamtomahawkx", "chillymosh", "mystypy"])

class YoutubeConverterError(commands.BadArgument):
    def __init__(self, link: yarl.URL):
        self.link = link
        super().__init__("Bad link!")

def youtube_converter(ctx: commands.Context, arg: str) -> yarl.URL:
    url = yarl.URL(arg) # this will raise if its an invalid URL.
    if url.host not in ("youtube.com", "youtu.be"):
        raise YoutubeConverterError(url)

    return url

@bot.command(name="share")
async def share_command(
    ctx: commands.Context,
    url: Annotated[yarl.URL, youtube_converter],
    hype: int,
    *,
    comment: str
) -> None:
    hype_level = "hype" if 0 < hype < 5 else "very hype"
    await ctx.send(f"{ctx.author.name} wants to share a {hype_level} link on {url.host}: {comment}")

bot.run()

Now, let’s pass a bad URL to it:

../_images/commands_errors_3.png

Great, we get our custom error! That’s our basic error handling, anything more complex is beyond this walkthrough.

Tip

Many Twitchio errors have additional context contained within them. If you wish to build your own error messages instead of the defaults, try checking the error’s attributes.

___

API Reference#

Bot#

class twitchio.ext.commands.Bot(token: str, *, prefix: Union[str, list, tuple, set, Callable, Coroutine], client_secret: Optional[str] = None, initial_channels: Optional[Union[list, tuple, Callable]] = None, heartbeat: Optional[float] = 30.0, retain_cache: Optional[bool] = True, **kwargs)#
add_cog(cog: Cog)#

Method which adds a cog to the bot.

Parameters

cog (Cog) – The cog instance to add to the bot.

Warning

This must be an instance of Cog.

add_command(command: Command)#

Method which registers a command for use by the bot.

Parameters

command (Command) – The command to register.

coroutine close()#

This function is a coroutine.

Cleanly disconnects from the twitch IRC server

command(*, name: ~typing.Optional[str] = None, aliases: ~typing.Optional[~typing.Union[list, tuple]] = None, cls=<class 'twitchio.ext.commands.core.Command'>, no_global_checks=False) Callable[[Callable], Command]#

Decorator which registers a command with the bot.

Commands must be a coroutine.

Parameters
  • name (str [Optional]) – The name of the command. By default if this is not supplied, the function name will be used.

  • aliases (Optional[Union[list, tuple]]) – The command aliases. This must be a list or tuple.

  • cls (class [Optional]) – The custom command class to override the default class. This must be similar to Command.

  • no_global_checks (Optional[bool]) – Whether or not the command should abide by global checks. Defaults to False, which checks global checks.

Raises

TypeError – cls is not type class.

coroutine connect()#

This function is a coroutine.

Connects to the twitch IRC server

create_user(user_id: int, user_name: str) PartialUser#

A helper method to create a twitchio.PartialUser from a user id and user name.

Parameters
  • user_id (int) – The id of the user

  • user_name (str) – The name of the user

Returns

twitchio.PartialUser

coroutine delete_videos(token: str, ids: List[int]) List[int]#

This function is a coroutine.

Delete videos from the api. Returns the video ids that were successfully deleted.

Parameters
  • token (str) – An oauth token with the channel:manage:videos scope

  • ids (List[int]) – A list of video ids from the channel of the oauth token to delete

Returns

List[int]

coroutine event_channel_join_failure(channel: str)#

This function is a coroutine.

Event called when the bot fails to join a channel.

Parameters

channel (str) – The channel name that was attempted to be joined.

coroutine event_channel_joined(channel: Channel)#

This function is a coroutine.

Event called when the bot joins a channel.

Parameters

channel (Channel) – The channel that was joined.

coroutine event_command_error(context: Context, error: Exception) None#

This function is a coroutine.

Event called when an error occurs during command invocation.

Parameters
  • context (Context) – The command context.

  • error (Exception) – The exception raised while trying to invoke the command.

coroutine event_error(error: Exception, data: Optional[str] = None)#

This function is a coroutine.

Event called when an error occurs while processing data.

Parameters
  • error (Exception) – The exception raised.

  • data (str) – The raw data received from Twitch. Depending on how this is called, this could be None.

Example

@bot.event()
async def event_error(error, data):
    traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
coroutine event_join(channel: Channel, user: User)#

This function is a coroutine.

Event called when a JOIN is received from Twitch.

Parameters
  • channel (Channel) – The channel associated with the JOIN.

  • user (User) – User object containing relevant information to the JOIN.

coroutine event_message(message: Message) None#

This function is a coroutine.

Event called when a PRIVMSG is received from Twitch.

Parameters

message (Message) – Message object containing relevant information.

coroutine event_mode(channel: Channel, user: User, status: str)#

This function is a coroutine.

Event called when a MODE is received from Twitch.

Parameters
  • channel (Channel) – Channel object relevant to the MODE event.

  • user (User) – User object containing relevant information to the MODE.

  • status (str) – The JTV status received by Twitch. Could be either o+ or o-. Indicates a moderation promotion/demotion to the User

coroutine event_notice(message: str, msg_id: Optional[str], channel: Optional[Channel])#

This function is a coroutine.

Event called with the NOTICE data received by Twitch.

Tip

For more information on NOTICE msg_ids visit: https://dev.twitch.tv/docs/irc/msg-id/

Parameters
  • message (str) – The message of the NOTICE.

  • msg_id (Optional[str]) – The msg_id that indicates what the NOTICE type.

  • channel (Optional[Channel]) – The channel the NOTICE message originated from.

Example

@bot.event()
async def event_notice(message, msg_id, channel):
    print(message)
coroutine event_part(user: User)#

This function is a coroutine.

Event called when a PART is received from Twitch.

Parameters

user (User) – User object containing relevant information to the PART.

coroutine event_raw_data(data: str)#

This function is a coroutine.

Event called with the raw data received by Twitch.

Parameters

data (str) – The raw data received from Twitch.

Example

@bot.event()
async def event_raw_data(data):
    print(data)
coroutine event_raw_notice(data: str)#

This function is a coroutine.

Event called with the raw NOTICE data received by Twitch.

Parameters

data (str) – The raw NOTICE data received from Twitch.

Example

@bot.event()
async def event_raw_notice(data):
    print(data)
coroutine event_raw_usernotice(channel: Channel, tags: dict)#

This function is a coroutine.

Event called when a USERNOTICE is received from Twitch. Since USERNOTICE’s can be fairly complex and vary, the following sub-events are available:

event_usernotice_subscription() : Called when a USERNOTICE Subscription or Re-subscription event is received.

Tip

For more information on how to handle USERNOTICE’s visit: https://dev.twitch.tv/docs/irc/tags/#usernotice-twitch-tags

Parameters
  • channel (Channel) – Channel object relevant to the USERNOTICE event.

  • tags (dict) – A dictionary with the relevant information associated with the USERNOTICE. This could vary depending on the event.

coroutine event_ready()#

This function is a coroutine.

Event called when the Bot has logged in and is ready.

Example

@bot.event()
async def event_ready():
    print(f'Logged into Twitch | {bot.nick}')
coroutine event_reconnect()#

This function is a coroutine.

Event called when twitch sends a RECONNECT notice. The library will automatically handle reconnecting when such an event is received

coroutine event_token_expired()#

This function is a coroutine.

A special event called when the oauth token expires. This is a hook into the http system, it will call this when a call to the api fails due to a token expiry. This function should return either a new token, or None. Returning None will cause the client to attempt an automatic token generation.

Note

This event is a callback hook. It is not a dispatched event. Any errors raised will be passed to the event_error() event.

coroutine event_usernotice_subscription(metadata)#

This function is a coroutine.

Event called when a USERNOTICE subscription or re-subscription event is received from Twitch.

Parameters

metadata (NoticeSubscription) – The object containing various metadata about the subscription event. For ease of use, this contains a User and Channel.

coroutine event_userstate(user: User)#

This function is a coroutine.

Event called when a USERSTATE is received from Twitch.

Parameters

user (User) – User object containing relevant information to the USERSTATE.

coroutine fetch_channel(broadcaster: str, token: Optional[str] = None)#

This function is a coroutine.

Retrieve channel information from the API.

Note

This will be deprecated in 3.0. It’s recommended to use fetch_channels() instead.

Parameters
  • broadcaster (str) – The channel name or ID to request from API. Returns empty dict if no channel was found.

  • token (Optional[str]) – An optional OAuth token to use instead of the bot OAuth token.

Returns

twitchio.ChannelInfo

coroutine fetch_channels(broadcaster_ids: List[int], token: Optional[str] = None)#

This function is a coroutine.

Retrieve information for up to 100 channels from the API.

Parameters
  • broadcaster_ids (List[int]) – The channel ids to request from API.

  • token (Optional[str]) – An optional OAuth token to use instead of the bot OAuth token

Returns

List[twitchio.ChannelInfo]

coroutine fetch_chatters_colors(user_ids: List[int], token: Optional[str] = None)#

This function is a coroutine.

Fetches the color of a chatter.

Parameters
  • user_ids (List[int]) – List of user ids to fetch the colors for

  • token (Optional[str]) – An optional user oauth token

Returns

List[twitchio.ChatterColor]

coroutine fetch_cheermotes(user_id: Optional[int] = None)#

This function is a coroutine.

Fetches cheermotes from the twitch API

Parameters

user_id (Optional[int]) – The channel id to fetch from.

Returns

List[twitchio.CheerEmote]

coroutine fetch_clips(ids: List[str])#

This function is a coroutine.

Fetches clips by clip id. To fetch clips by user id, use twitchio.PartialUser.fetch_clips()

Parameters

ids (List[str]) – A list of clip ids

Returns

List[twitchio.Clip]

coroutine fetch_content_classification_labels(locale: Optional[str] = None)#

This function is a coroutine.

Fetches information about Twitch content classification labels.

Parameters

locale (Optional[str]) – Locale for the Content Classification Labels. You may specify a maximum of 1 locale. Default: “en-US”

Returns

List[twitchio.ContentClassificationLabel]

coroutine fetch_games(ids: Optional[List[int]] = None, names: Optional[List[str]] = None, igdb_ids: Optional[List[int]] = None) List[Game]#

This function is a coroutine.

Fetches games by id or name. At least one id or name must be provided

Parameters
  • ids (Optional[List[int]]) – An optional list of game ids

  • names (Optional[List[str]]) – An optional list of game names

  • igdb_ids (Optional[List[int]]) – An optional list of IGDB game ids

Returns

List[twitchio.Game]

coroutine fetch_global_chat_badges()#

This function is a coroutine.

Fetches Twitch’s list of chat badges, which users may use in any channel’s chat room.

Returns

List[twitchio.ChatBadge]

coroutine fetch_global_emotes()#

This function is a coroutine.

Fetches global emotes from the twitch API

Returns

List[twitchio.GlobalEmote]

coroutine fetch_streams(user_ids: Optional[List[int]] = None, game_ids: Optional[List[int]] = None, user_logins: Optional[List[str]] = None, languages: Optional[List[str]] = None, token: Optional[str] = None, type: typing_extensions.Literal[all, live] = 'all')#

This function is a coroutine.

Fetches live streams from the helix API

Parameters
  • user_ids (Optional[List[int]]) – user ids of people whose streams to fetch

  • game_ids (Optional[List[int]]) – game ids of streams to fetch

  • user_logins (Optional[List[str]]) – user login names of people whose streams to fetch

  • languages (Optional[List[str]]) – language for the stream(s). ISO 639-1 or two letter code for supported stream language

  • token (Optional[str]) – An optional OAuth token to use instead of the bot OAuth token

  • type (Literal["all", "live"]) – One of "all" or "live". Defaults to "all". Specifies what type of stream to fetch.

Returns

List[twitchio.Stream]

coroutine fetch_tags(ids: Optional[List[str]] = None)#

This function is a coroutine.

Fetches stream tags.

Parameters

ids (Optional[List[str]]) – The ids of the tags to fetch

Returns

List[twitchio.Tag]

coroutine fetch_teams(team_name: Optional[str] = None, team_id: Optional[str] = None)#

This function is a coroutine.

Fetches information for a specific Twitch Team.

Parameters
  • name (Optional[str]) – Team name to fetch

  • id (Optional[str]) – Team id to fetch

Returns

List[twitchio.Team]

coroutine fetch_top_games() List[Game]#

This function is a coroutine.

Fetches the top games from the api

Returns

List[twitchio.Game]

coroutine fetch_users(names: Optional[List[str]] = None, ids: Optional[List[int]] = None, token: Optional[str] = None, force=False) List[User]#

This function is a coroutine.

Fetches users from the helix API

Parameters
  • names (Optional[List[str]]) – usernames of people to fetch

  • ids (Optional[List[str]]) – ids of people to fetch

  • token (Optional[str]) – An optional OAuth token to use instead of the bot OAuth token

  • force (bool) – whether to force a fetch from the api, or check the cache first. Defaults to False

Returns

List[twitchio.User]

coroutine fetch_videos(ids: Optional[List[int]] = None, game_id: Optional[int] = None, user_id: Optional[int] = None, period=None, sort=None, type=None, language=None)#

This function is a coroutine.

Fetches videos by id, game id, or user id

Parameters
  • ids (Optional[List[int]]) – A list of video ids

  • game_id (Optional[int]) – A game to fetch videos from

  • user_id (Optional[int]) – A user to fetch videos from. See twitchio.PartialUser.fetch_videos()

  • period (Optional[str]) – The period for which to fetch videos. Valid values are all, day, week, month. Defaults to all. Cannot be used when video id(s) are passed

  • sort (str) – Sort orders of the videos. Valid values are time, trending, views, Defaults to time. Cannot be used when video id(s) are passed

  • type (Optional[str]) – Type of the videos to fetch. Valid values are upload, archive, highlight. Defaults to all. Cannot be used when video id(s) are passed

  • language (Optional[str]) – Language of the videos to fetch. Must be an ISO-639-1 two letter code. Cannot be used when video id(s) are passed

Returns

List[twitchio.Video]

classmethod from_client_credentials(client_id: str, client_secret: str, *, loop: Optional[AbstractEventLoop] = None, heartbeat: Optional[float] = 30.0, prefix: Union[str, list, tuple, set, Callable, Coroutine] = '!') Bot#

creates a client application token from your client credentials.

Parameters
  • client_id (str) – Your application’s Client ID.

  • client_secret (str) – An application Client Secret used to generate Access Tokens automatically.

  • loop (Optional[asyncio.AbstractEventLoop]) – The event loop the client will use to run.

  • heartbeat (Optional[float]) – The heartbeat interval. Defaults to 30.

  • prefix (Union[str, list, tuple, set, Callable, Coroutine]) – The bots prefix. Defaults to “!”.

Returns

A new Bot instance

get_channel(name: str) Optional[Channel]#

Retrieve a channel from the cache.

Parameters

name (str) – The channel name to retrieve from cache. Returns None if no channel was found.

Returns

Channel

get_cog(name: str) Optional[Cog]#

Retrieve a Cog from the bots loaded Cogs.

Could be None if the Cog was not found.

Returns

Optional[Cog]

get_command(name: str) Optional[Command]#

Method which retrieves a registered command.

Parameters

name (str) – The name or alias of the command to retrieve.

Returns

Optional[Command]

coroutine get_context(message, *, cls=None)#

Get a Context object from a message.

Parameters
  • message (Message) – The message object to get context for.

  • cls – The class to return. Defaults to Context. Its constructor must take message, prefix, valid, and bot as arguments.

Returns

An instance of cls.

Raises

.CommandNotFound

coroutine get_webhook_subscriptions()#

This function is a coroutine.

Fetches your current webhook subscriptions. Requires your bot to be logged in with an app access token.

Returns

List[twitchio.WebhookSubscription]

coroutine global_after_invoke(ctx: Context) None#

This function is a coroutine.

Method which is called after any command is invoked regardless if it failed or not.

This method is useful for cleaning up things after command invocation. E.g Database connections.

Parameters

ctx – The context used for command invocation.

Note

The global_after_invoke is called only after the command successfully invokes.

coroutine global_before_invoke(ctx)#

This function is a coroutine.

Method which is called before any command is about to be invoked.

This method is useful for setting up things before command invocation. E.g Database connections or retrieving tokens for use in the command.

Parameters

ctx – The context used for command invocation.

Examples

async def global_before_invoke(self, ctx):
    # Make a database query for example to retrieve a specific token.
    token = db_query()

    ctx.token = token

async def my_command(self, ctx):
    data = await self.create_clip(ctx.token, ...)

Note

The global_before_invoke is called before any other command specific hooks.

coroutine handle_commands(message)#

This function is a coroutine.

This method handles commands sent from chat and invokes them.

By default, this coroutine is called within the Bot.event_message() event. If you choose to override Bot.event_message() then you need to invoke this coroutine in order to handle commands.

Parameters

message (Message) – The message object to get content of and context for.

coroutine join_channels(channels: Union[List[str], Tuple[str]])#

This function is a coroutine.

Join the specified channels.

Parameters

channels (Union[List[str], Tuple[str]]) – The channels in either a list or tuple form to join.

load_module(name: str) None#

Method which loads a module and it’s cogs.

Parameters

name (str) – The name of the module to load in dot.path format.

coroutine part_channels(channels: Union[List[str], Tuple[str]])#

This function is a coroutine.

Part the specified channels.

Parameters

channels (Union[List[str], Tuple[str]]) – The channels in either a list or tuple form to part.

reload_module(name: str)#

Method which reloads a module and it’s cogs.

Parameters

name (str) – The name of the module to unload in dot.path format.

Note

This is roughly equivalent to bot.unload_module(…) then bot.load_module(…).

remove_cog(cog_name: str)#

Method which removes a cog from the bot. :param cog_name: The name of the cog to remove. :type cog_name: str

remove_command(name: str)#

Method which removes a registered command

Parameters

name (str) – the name or alias of the command to delete.

Returns

None

Raises

.CommandNotFound

run()#

A blocking function that starts the asyncio event loop, connects to the twitch IRC server, and cleans up when done.

coroutine search_categories(query: str)#

This function is a coroutine.

Searches twitches categories

Parameters

query (str) – The query to search for

Returns

List[twitchio.Game]

coroutine search_channels(query: str, *, live_only=False)#

This function is a coroutine.

Searches channels for the given query

Parameters
  • query (str) – The query to search for

  • live_only (bool) – Only search live channels. Defaults to False

Returns

List[twitchio.SearchUser]

coroutine start()#

This function is a coroutine.

Connects to the twitch IRC server, and cleanly disconnects when done.

unload_module(name: str) None#

Method which unloads a module and it’s cogs.

Parameters

name (str) – The name of the module to unload in dot.path format.

coroutine update_chatter_color(token: str, user_id: int, color: str)#

This function is a coroutine.

Updates the color of the specified user in the specified channel/broadcaster’s chat.

Parameters
  • token (str) – An oauth token with the user:manage:chat_color scope.

  • user_id (int) – The ID of the user whose color is being updated, this must match the user ID in the token.

  • color (str) – Turbo and Prime users may specify a named color or a Hex color code like #9146FF. Please see the Twitch documentation for more information.

Returns

None

coroutine wait_for(event: str, predicate: ~typing.Callable[[], bool] = <function Client.<lambda>>, *, timeout=60.0) Tuple[Any]#

This function is a coroutine.

Waits for an event to be dispatched, then returns the events data

Parameters
  • event (str) – The event to wait for. Do not include the event_ prefix

  • predicate (Callable[[...], bool]) – A check that is fired when the desired event is dispatched. if the check returns false, the waiting will continue until the timeout.

  • timeout (int) – How long to wait before timing out and raising an error.

Returns

The arguments passed to the event.

wait_for_ready() Coroutine[Any, Any, bool]#

This function is a coroutine.

Waits for the underlying connection to finish startup

Returns

bool The state of the underlying flag. This will always be True

property cogs: Mapping[str, Cog]#

The currently loaded cogs.

property commands#

The currently loaded commands.

property connected_channels: List[Channel]#

A list of currently connected Channel

property events#

A mapping of events name to coroutine.

property nick#

The IRC bots nick.

property user_id#

The IRC bot user id.

Context#

class twitchio.ext.commands.Context(message: Message, bot: Bot, **attrs)#

A class that represents the context in which a command is being invoked under.

This class contains the meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

message#

The message that triggered the command being executed.

Type

Message

channel#

The channel the command was invoked in.

Type

Channel

author#

The Chatter object of the user in chat that invoked the command.

Type

Union[PartialChatter, Chatter]

prefix#

The prefix that was used to invoke the command.

Type

Optional[str]

command#

The command that was invoked

Type

Optional[Command]

cog#

The cog that contains the command that was invoked.

Type

Optional[Cog]

args#

List of arguments that were passed to the command.

Type

Optional[List[Any]]

kwargs#

List of kwargs that were passed to the command.

Type

Optional[Dict[str, Any]]

view#

StringParser object that breaks down the command string received.

Type

Optional[StringParser]

bot#

The bot that contains the command that was invoked.

Type

Bot

get_user(name: str) Optional[Union[PartialUser, User]]#

Retrieve a user from the channels user cache.

Parameters

name (str) – The user’s name to try and retrieve.

Returns

Union[twitchio.user.User, twitchio.user.PartialUser] – Could be a twitchio.user.PartialUser depending on how the user joined the channel. Returns None if no user was found.

coroutine reply(content: str)#

This function is a coroutine.

Send a message in reply to the user who sent a message in the destination associated with the dataclass.

Destination will be the context of which the message/command was sent.

Parameters

content (str) – The content you wish to send as a message. The content must be a string.

Raises

InvalidContent – Invalid content.

coroutine send(content: str)#

This function is a coroutine.

Send a message to the destination associated with the dataclass.

Destination will either be a channel or user.

Parameters

content (str) – The content you wish to send as a message. The content must be a string.

Raises

InvalidContent – Invalid content.

property chatters: Optional[Set[Chatter]]#

The channels current chatters.

property users: Optional[Set[Chatter]]#

Alias to chatters.

Command#

Attributes
class twitchio.ext.commands.Command(name: str, func: Callable, **attrs)#

A class for implementing bot commands.

Parameters
  • name (str) – The name of the command.

  • func (Callable) – The coroutine that executes when the command is invoked.

name#

The name of the command.

Type

str

cog#

The cog this command belongs to.

Type

Cog

aliases#

Aliases that can be used to also invoke the command.

Type

Optional[Union[list, tuple]]

Cog#

Attributes
Methods
class twitchio.ext.commands.Cog#

Class used for creating a TwitchIO Cog.

Cogs help organise code and provide powerful features for creating bots. Cogs can contain commands, events and special cog specific methods to help with checks, before and after command invocation hooks, and cog error handlers.

To use a cog simply subclass Cog and add it. Once added, cogs can be un-added and re-added live.

Examples

# In modules/test.py

from twitchio.ext import commands

class MyCog(commands.Cog):

    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.command()
    async def hello(self, ctx: commands.Context):
        await ctx.send(f"Hello, {ctx.author.name}!")

    @commands.Cog.event()
    async def event_message(self, message):
        # An event inside a cog!
        if message.echo:
            return

        print(message.content)


def prepare(bot: commands.Bot):
    # Load our cog with this module...
    bot.add_cog(MyCog(bot))
coroutine cog_check(ctx: Context) bool#

A cog-wide check which is ran everytime a command from this Cog is invoked.

Parameters

ctx (Context) – The context used to try and invoke this command.

Notes

Note

This method must return True/False or raise. If this check returns False or raises, it will fail and an exception will be propagated to error handlers.

coroutine cog_command_error(ctx: Context, exception: Exception) None#

Method invoked when an error is raised in one of this cogs commands.

Parameters
  • ctx (Context) – The context around the invoked command.

  • exception (Exception) – The exception raised.

classmethod event(event: Optional[str] = None) Callable[[function], CogEvent]#

Add an event listener to this Cog.

Examples

class MyCog(commands.Cog):

    def __init__(...):
        ...

    @commands.Cog.event()
    async def event_message(self, message: twitchio.Message):
        print(message.content)

    @commands.Cog.event("event_ready")
    async def bot_is_ready(self):
        print('Bot is ready!')
property commands: dict#

The commands associated with this cog as a mapping.

property name: str#

This cogs name.

Cooldowns#

class twitchio.ext.commands.Bucket(value)#

Enum values for the different cooldown buckets.

Parameters
  • default (enum.Enum) – The default bucket.

  • channel (enum.Enum) – Cooldown is shared amongst all chatters per channel.

  • member (enum.Enum) – Cooldown operates on a per channel basis per user.

  • user (enum.Enum) – Cooldown operates on a user basis across all channels.

  • subscriber (enum.Enum) – Cooldown for subscribers.

  • mod (enum.Enum) – Cooldown for mods.

class twitchio.ext.commands.Cooldown(rate: int, per: float, bucket: Bucket)#

Cooldown decorator values.

Parameters
  • rate (int) – How many times the command can be invoked before triggering a cooldown inside a time frame.

  • per (float) – The amount of time in seconds to wait for a cooldown when triggered.

  • bucket (Bucket) – The bucket that the cooldown is in.

Examples

# Restrict a command to once every 10 seconds on a per channel basis.
@commands.cooldown(rate=1, per=10, bucket=commands.Bucket.channel)
@commands.command()
async def my_command(self, ctx: commands.Context):
    pass

# Restrict a command to once every 30 seconds for each individual channel a user is in.
@commands.cooldown(rate=1, per=30, bucket=commands.Bucket.member)
@commands.command()
async def my_command(self, ctx: commands.Context):
    pass

# Restrict a command to 5 times every 60 seconds globally for a user.
@commands.cooldown(rate=5, per=60, bucket=commands.Bucket.user)
@commands.command()
async def my_command(self, ctx: commands.Context):
    pass