Bot

class twitchio.ext.commands.Bot(*, client_id: str, client_secret: str, bot_id: str, owner_id: str | None = None, prefix: PrefixT, **options: Unpack[BotOptions])

The TwitchIO commands.Bot class.

The Bot is an extension of and inherits from twitchio.Client and comes with additonal powerful features for creating and managing bots on Twitch.

Unlike twitchio.Client, the Bot class allows you to easily make use of built-in the commands ext.

The easiest way of creating and using a bot is via subclassing, some examples are provided below.

Note

Any examples contained in this class which use twitchio.Client can be changed to commands.Bot.

Parameters
  • client_id (str) – The client ID of the application you registered on the Twitch Developer Portal.

  • client_secret (str) – The client secret of the application you registered on the Twitch Developer Portal. This must be associated with the same client_id.

  • bot_id (str) – The User ID associated with the Bot Account. Unlike on Client this is a required argument on Bot.

  • owner_id (str | None) – An optional str which is the User ID associated with the owner of this bot. This should be set to your own user accounts ID, but is not required. Defaults to None.

  • prefix (str | Iterabale[str] | Coroutine[Any, Any, str | Iterable[str]]) –

    The prefix(es) to listen to, to determine whether a message should be treated as a possible command.

    This can be a str, an iterable of str or a coroutine which returns either.

    This is a required argument, common prefixes include: "!" or "?".

Example

import asyncio
import logging

import twitchio
from twitchio import eventsub
from twitchio.ext import commands

LOGGER: logging.Logger = logging.getLogger("Bot")

class Bot(commands.Bot):

    def __init__(self) -> None:
        super().__init__(client_id="...", client_secret="...", bot_id="...", owner_id="...", prefix="!")

    # Do some async setup, as an example we will load a component and subscribe to some events...
    # Passing the bot to the component is completely optional...
    async def setup_hook(self) -> None:

        # Listen for messages on our channel...
        # You need appropriate scopes, see the docs on authenticating for more info...
        payload = eventsub.ChatMessageSubscription(broadcaster_user_id=self.owner_id, user_id=self.bot_id)
        await self.subscribe_websocket(payload=payload)

        await self.add_component(SimpleCommands(self))
        LOGGER.info("Finished setup hook!")

class SimpleCommands(commands.Component):

    def __init__(self, bot: Bot) -> None:
        self.bot = bot

    @commands.command()
    async def hi(self, ctx: commands.Context) -> None:
        '''Command which sends you a hello.'''
        await ctx.reply(f"Hello {ctx.chatter}!")

    @commands.command()
    async def say(self, ctx: commands.Context, *, message: str) -> None:
        '''Command which repeats what you say: !say I am an apple...'''
        await ctx.send(message)

def main() -> None:
    # Setup logging, this is optional, however a nice to have...
    twitchio.utils.setup_logging(level=logging.INFO)

    async def runner() -> None:
        async with Bot() as bot:
            await bot.start()

    try:
        asyncio.run(runner())
    except KeyboardInterrupt:
        LOGGER.warning("Shutting down due to Keyboard Interrupt...")

main()
property bot_id: str

Property returning the ID of the bot.

You must ensure you set this via the keyword argument bot_id="..." in the constructor of this class.

Returns

The bot_id that was set.

Return type

str

property owner_id: str | None

Property returning the ID of the user who owns this bot.

This can be set via the keyword argument owner_id="..." in the constructor of this class.

Returns

The owner ID that has been set. None if this has not been set.

Return type

str | None

async close(**options: Any) None

This function is a coroutine.

Method which closes the Client gracefully.

This method is called for you automatically when using run() or when using the client with the async context-manager, E.g: async with client:

You can override this method to implement your own clean-up logic, however you should call await super().close() when doing this.

Parameters
  • *

  • save_tokens (bool | None) – An optional bool override which allows overriding the identical keyword-argument set in either run(), start() or login() to call the save_tokens() coroutine. Defaults to None which won’t override.

Examples

async def close(self) -> None:
    # Own clenup logic...
    ...
    await super().close()
async add_component(component: Component, /) None

This function is a coroutine.

Method to add a commands.Component to the bot.

All Command and listener()’s in the component will be loaded alongside the component.

If this method fails, including if component_load() fails, everything will be rolled back and cleaned up and a commands.ComponentLoadError will be raised from the original exception.

Parameters

component (Component) – The component to add to the bot.

Raises

ComponentLoadError – The component failed to load.

async remove_component(name: str, /) Component | None

This function is a coroutine.

Method to remove a commands.Component from the bot.

All Command and listener()’s in the component will be unloaded alongside the component.

If this method fails when component_teardown() fails, the component will still be unloaded completely from the bot, with the exception being logged.

Parameters

name (str) – The name of the component to unload.

Returns

The component that was removed. None if the component was not found.

Return type

Component | None

get_component(name: str, /) Component | None

Retrieve a Component from the bots loaded Component. This will return None if the Component was not found.

Parameters

name (str) – The name of the Component.

Return type

Component | None

get_context(message: ChatMessage, *, cls: Any = None) Any

Method to create and retrieve a Context object from a twitchio.ChatMessage.

This method can be overriden to accept a custom class which inherits from Context for use within the command invocation process, instead of the default.

Parameters
  • message (ChatMessage) – The message to construct a Context or derivative from.

  • cls (Any) – A custom class to use as the context. This should inherit from Context.

Examples

class CustomContext(commands.Context):
    ...

class Bot(commands.Bot):

    def get_context(self, message: twitchio.ChatMessage, *, cls: Any = None) -> CustomContext:
        cls = cls or CustomContext
        return cls(message, bot=self)

@commands.command()
async def test(ctx: CustomContext) -> None:
    ...
async event_command_error(payload: CommandErrorPayload) None

An event called when an error occurs during command invocation.

By default this event logs the exception raised.

You can override this method, however you should take care to log unhandled exceptions.

Parameters

payload (commands.CommandErrorPayload) – The payload associated with this event.

async before_invoke(ctx: Context) None

A pre invoke hook for all commands that have been added to the bot.

Commands from Component’s are included, however if you wish to control them separately, see: component_before_invoke().

The pre-invoke hook will be called directly before a valid command is scheduled to run. If this coroutine errors, a CommandHookError will be raised from the original error.

Useful for setting up any state like database connections or http clients for command invocation.

The order of calls with the pre-invoke hooks is:

Note

This hook only runs after successfully parsing arguments and passing all guards associated with the command, component (if applicable) and bot.

Parameters

ctx (commands.Context) – The context associated with command invocation, before being passed to the command.

async after_invoke(ctx: Context) None

A post invoke hook for all commands that have been added to the bot.

Commands from Component’s are included, however if you wish to control them separately, see: component_after_invoke().

The post-invoke hook will be called after a valid command has been invoked. If this coroutine errors, a CommandHookError will be raised from the original error.

Useful for cleaning up any state like database connections or http clients.

The order of calls with the post-invoke hooks is:

Note

This hook is always called even when the Command fails to invoke but similar to before_invoke() only if parsing arguments and guards are successfully completed.

Parameters

ctx (commands.Context) – The context associated with command invocation, after being passed through the command.

async global_guard(ctx: Context, /) bool

This function is a coroutine.

A global guard applied to all commmands added to the bot.

This coroutine function should take in one parameter Context the context surrounding command invocation, and return a bool indicating whether a command should be allowed to run.

If this function returns False, the chatter will not be able to invoke the command and an error will be raised. If this function returns True the chatter will be able to invoke the command, assuming all the other guards also pass their predicate checks.

See: guard() for more information on guards, what they do and how to use them.

Note

This is the first guard to run, and is applied to every command.

Important

Unlike command specific guards or commands.Component.guard(), this function must be always be a coroutine.

This coroutine is intended to be overriden when needed and by default always returns True.

Parameters

ctx (commands.Context) – The context associated with command invocation.

Raises

GuardFailure – The guard predicate returned False and prevented the chatter from using the command.

async subscribe_webhook(payload: SubscriptionPayload, *, as_bot: bool = True, token_for: str | PartialUser | None, callback_url: str | None = None, eventsub_secret: str | None = None) SubscriptionResponse | None

This function is a coroutine.

Subscribe to an EventSub Event via Webhook.

Note

For more information on how to setup your bot with webhooks, see: …

Important

Usually you wouldn’t use webhooks to subscribe to the ChatMessageSubscription subscription.

Consider using subscribe_websocket() for this subscription.

Parameters
  • payload (SubscriptionPayload) – The payload which should include the required conditions to subscribe to.

  • as_bot (bool) – Whether to subscribe to this event using the user token associated with the provided Client.bot_id. If this is set to True and bot_id has not been set, this method will raise ValueError. Defaults to False on Client but will default to True on Bot

  • token_for (str | PartialUser | None) –

    An optional User ID, or PartialUser, that will be used to find an appropriate managed user token for this request.

    If as_bot is True, this is always the token associated with the bot_id account. Defaults to None.

    See: add_token() to add managed tokens to the client. If this paramter is not provided or None, the default app token is used.

  • callback_url (str | None) – An optional url to use as the webhook callback_url for this subscription. If you are using one of the built-in web adapters, you should not need to set this. See: (web adapter docs link) for more info.

  • eventsub_secret (str | None) – An optional str to use as the eventsub_secret, which is required by Twitch. If you are using one of the built-in web adapters, you should not need to set this. See: (web adapter docs link) for more info.

Return type

SubscriptionResponse

Raises
  • ValueError – One of the provided parameters is incorrect or incompatible.

  • HTTPException – An error was raised while making the subscription request to Twitch.

async subscribe_websocket(payload: SubscriptionPayload, *, as_bot: bool = True, token_for: str | PartialUser | None = None, socket_id: str | None = None) SubscriptionResponse | None

This function is a coroutine.

Subscribe to an EventSub Event via Websockets.

Note

See: … for more information and recipes on using eventsub.

Parameters
  • payload (twitchio.SubscriptionPayload) – The payload which should include the required conditions to subscribe to.

  • as_bot (bool) – Whether to subscribe to this event using the user token associated with the provided Client.bot_id. If this is set to True and bot_id has not been set, this method will raise ValueError. Defaults to False on Client but will default to True on Bot

  • token_for (str | PartialUser | None) –

    An optional User ID, or PartialUser, that will be used to find an appropriate managed user token for this request.

    If as_bot is True, this is always the token associated with the bot_id account. Defaults to None.

    See: add_token() to add managed tokens to the client. If this paramter is not provided or None, the default app token is used.

  • socket_id (str | None) – An optional str corresponding to an exisiting and connected websocket session, to use for this subscription. You usually do not need to pass this parameter as TwitchIO delegates subscriptions to websockets as needed. Defaults to None.

Return type

SubscriptionResponse

Raises
  • ValueError – One of the provided parameters is incorrect or incompatible.

  • HTTPException – An error was raised while making the subscription request to Twitch.

async load_module(name: str, *, package: str | None = None) None

This function is a coroutine.

Loads a module.

A module is a python module that contains commands, cogs, or listeners.

A module must have a global coroutine, setup defined as the entry point on what to do when the module is loaded. The coroutine takes a single argument, the bot.

Changed in version 3.0: This method is now a coroutine.

Parameters
  • name (str) – The module to load. It must be dot separated like regular Python imports accessing a sub-module. e.g. foo.bar if you want to import foo/bar.py.

  • package (str | None) – The package name to resolve relative imports with. This is required when loading an extension using a relative path. e.g. .foo.bar. Defaults to None.

Raises
async unload_module(name: str, *, package: str | None = None) None

This function is a coroutine.

Unloads a module.

When the module is unloaded, all commands, listeners and components are removed from the bot, and the module is un-imported.

You can add an optional global coroutine of teardown to the module to do miscellaneous clean-up if necessary. This also takes a single paramter of the bot, similar to setup.

Changed in version 3.0: This method is now a coroutine.

Parameters
  • name (str) – The module to unload. It must be dot separated like regular Python imports accessing a sub-module. e.g. foo.bar if you want to import foo/bar.py.

  • package (str | None) – The package name to resolve relative imports with. This is required when unloading an extension using a relative path. e.g. .foo.bar. Defaults to None.

Raises

ModuleNotLoaded – The module was not loaded.

async reload_module(name: str, *, package: str | None = None) None

This function is a coroutine.

Atomically reloads a module.

This attempts to unload and then load the module again, in an atomic way. If an operation fails mid reload then the bot will revert back to the prior working state.

Changed in version 3.0: This method is now a coroutine.

Parameters
  • name (str) – The module to unload. It must be dot separated like regular Python imports accessing a sub-module. e.g. foo.bar if you want to import foo/bar.py.

  • package (str | None) – The package name to resolve relative imports with. This is required when unloading an extension using a relative path. e.g. .foo.bar. Defaults to None.

Raises
  • ModuleNotLoaded – The module was not loaded.

  • ModuleNotFoundError – The module could not be imported. Also raised if module could not be resolved using the package parameter.

  • ModuleLoadFailure – There was an error loading the module.

  • NoEntryPointError – The module does not have a setup coroutine.

  • TypeError – The module’s setup function is not a coroutine.

property modules: Mapping[str, types.ModuleType]

A read-only mapping of extension name to extension.

Type

Mapping[str, types.ModuleType]

add_command(command: Command[Component_T, ...], /) None

Add a Command object to the mixin.

For group commands you would usually use the command() decorator instead.

See: command().

add_listener(listener: Callable[..., Coroutine[Any, Any, None]], *, event: str | None = None) None

Method to add an event listener to the client.

See: listen() for more information on event listeners and for a decorator version of this function.

Parameters
  • listener (Callable[..., Coroutine[Any, Any, None]]) – The coroutine to assign as the callback for the listener.

  • event (str | None) – An optional str which indicates which event to listen to. This should include the event_ prefix. Defaults to None which uses the coroutine function name passed instead.

Raises
  • ValueError – The event string passed should start with event_.

  • ValueError – The event string passed must not == event_.

  • TypeError – The listener callback must be a coroutine function.

async add_token(token: str, refresh: str) ValidateTokenPayload

This function is a coroutine.

Adds a token and refresh-token pair to the client to be automatically managed.

After successfully adding a token to the client, the token will be automatically revalidated and refreshed both when required and periodically.

This method is automatically called in the event_oauth_authorized() event, when a token is authorized by a user via the built-in OAuth adapter.

You can override the event_oauth_authorized() or this method to implement custom functionality such as storing the token in a database.

Storing your tokens safely is highly recommended and required to prevent users needing to reauthorize your application after restarts.

Note

Both token and refresh are required parameters.

Parameters
  • token (str) – The User-Access token to add.

  • refresh (str) – The refresh token associated with the User-Access token to add.

Examples

class Client(twitchio.Client):

    async def add_token(self, token: str, refresh: str) -> None:
        # Code to add token to database here...
        ...

        # Adds the token to the client...
        await super().add_token(token, refresh)
property case_insensitive: bool

Property returning a bool indicating whether this Mixin is using case insensitive commands.

property commands: dict[str, Union[twitchio.ext.commands.core.Command[Component_T, ...], twitchio.ext.commands.core.Group[Any, ...]]]

Property returning the mapping of currently added Command and Group associated with this Mixin.

This mapping includes aliases as keys.

Note

See: unique_commands for a set of commands without duplicates due to aliases.

create_partialuser(user_id: str | int, user_login: str | None = None) PartialUser

Helper method used to create twitchio.PartialUser objects.

PartialUser’s are used to make HTTP requests regarding users on Twitch.

New in version 3.0.0: This has been renamed from create_user to create_partialuser.

Parameters
  • user_id (str | int) – ID of the user you wish to create a PartialUser for.

  • user_login (str | None) – Login name of the user you wish to create a PartialUser for, if available.

Returns

A PartialUser object.

Return type

PartialUser

async delete_all_eventsub_subscriptions(*, token_for: str | twitchio.user.PartialUser | None = None) None

This function is a coroutine.

Delete all eventsub subscriptions.

Parameters

token_for (str | PartialUser | None) –

Do not pass this if you wish to delete webhook subscriptions, which are what usually require deleting.

For websocket subscriptions, provide the user ID, or PartialUser, associated with the subscription.

async delete_eventsub_subscription(id: str, *, token_for: str | twitchio.user.PartialUser | None = None) None

This function is a coroutine.

Delete an eventsub subscription.

Parameters
  • id (str) – The ID of the eventsub subscription to delete.

  • token_for (str | PartialUser | None) –

    Do not pass this if you wish to delete webhook subscriptions, which are what usually require deleting.

    For websocket subscriptions, provide the user ID, or PartialUser, associated with the subscription.

async delete_videos(*, ids: list[str | int], token_for: str | twitchio.user.PartialUser) list[str]

This function is a coroutine.

Deletes one or more videos for a specific broadcaster.

Note

You may delete past broadcasts, highlights, or uploads.

Note

This requires a user token with the scope channel:manage:videos.

The limit is to delete 5 ids at a time. When more than 5 ids are provided, an attempt to delete them in chunks is made.

If any of the videos fail to delete in a chunked request, no videos will be deleted in that chunk.

Parameters
  • ids (list[str | int] | None) – A list of video IDs to delete.

  • token_for (str | PartialUser) –

    The User ID, or PartialUser, that will be used to find an appropriate managed user token for this request. The token must inlcude the channel:manage:videos scope.

    See: add_token() to add managed tokens to the client.

Returns

A list of Video IDs that were successfully deleted.

Return type

list[str]

async event_error(payload: EventErrorPayload) None

Event called when an error occurs in an event or event listener.

This event can be overriden to handle event errors differently. By default, this method logs the error and ignores it.

Warning

If an error occurs in this event, it will be ignored and logged. It will NOT re-trigger this event.

Parameters

payload (EventErrorPayload) – A payload containing the Exception, the listener, and the original payload.

async fetch_badges(*, token_for: str | twitchio.user.PartialUser | None = None) list[twitchio.models.chat.ChatBadge]

This function is a coroutine.

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

Parameters
  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

  • badges (To fetch a specific broadcaster's chat) –

  • see (fetch_badges()) –

Returns

A list of ChatBadge objects

Return type

list[twitchio.ChatBadge]

async fetch_channels(broadcaster_ids: list[str | int], *, token_for: str | twitchio.user.PartialUser | None = None) list[twitchio.models.channels.ChannelInfo]

This function is a coroutine.

Retrieve channel information from the API.

Parameters
  • broadcaster_ids (list[str | int]) – A list of channel IDs to request from API. You may specify a maximum of 100 IDs.

  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

Returns

A list of ChannelInfo objects.

Return type

list[ChannelInfo]

async fetch_chatters_color(user_ids: list[str | int], *, token_for: str | twitchio.user.PartialUser | None = None) list[twitchio.models.chat.ChatterColor]

This function is a coroutine.

Fetches the color of a chatter.

Changed in version 3.0: Removed the token parameter. Added the token_for parameter.

Parameters
  • user_ids (list[str | int]) – A list of user ids to fetch the colours for.

  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

Returns

A list of ChatterColor objects associated with the passed user IDs.

Return type

list[ChatterColor]

async fetch_cheermotes(*, broadcaster_id: int | str | None = None, token_for: str | twitchio.user.PartialUser | None = None) list[twitchio.models.bits.Cheermote]

This function is a coroutine.

Fetches a list of Cheermotes that users can use to cheer Bits in any Bits-enabled channel’s chat room.

Cheermotes are animated emotes that viewers can assign Bits to. If a broadcaster_id is not specified then only global cheermotes will be returned.

If the broadcaster uploaded Cheermotes, the type attribute will be set to channel_custom.

Parameters
  • broadcaster_id (str | int | None) – The ID of the broadcaster whose custom Cheermotes you want to fetch. If not provided or None then you will fetch global Cheermotes. Defaults to None

  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

Returns

A list of Cheermote objects.

Return type

list[Cheermote]

async fetch_classifications(locale: str = 'en-US', *, token_for: str | twitchio.user.PartialUser | None = None) list[twitchio.models.ccls.ContentClassificationLabel]

This function is a coroutine.

Fetches information about Twitch content classification labels.

Parameters
  • locale (str) – Locale for the Content Classification Labels.

  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

Returns

A list of ContentClassificationLabel objects.

Return type

list[ContentClassificationLabel]

await .fetch_clips(...) -> list[T]
async for item in .fetch_clips(...):

async
fetch_clips(*, game_id: str | None = None, clip_ids: list[str] | None = None, started_at: datetime.datetime | None = None, ended_at: datetime.datetime | None = None, featured: bool | None = None, token_for: str | PartialUser | None = None, first: int = 20, max_results: int | None = None) HTTPAsyncIterator[Clip]

This function returns a HTTPAsyncIterator

Fetches clips by the provided clip ids or game id.

Parameters
  • game_id (list[str | int] | None) – A game id to fetch clips from.

  • clip_ids (list[str] | None) – A list of specific clip IDs to fetch. The Maximum amount you can request is 100.

  • started_at (datetime.datetime) – The start date used to filter clips.

  • ended_at (datetime.datetime) – The end date used to filter clips. If not specified, the time window is the start date plus one week.

  • featured (bool | None) –

    When this parameter is True, this method returns only clips that are featured. When this parameter is False, this method returns only clips that are not featured.

    Othwerise if this parameter is not provided or None, all clips will be returned. Defaults to None.

  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

  • first (int) – The maximum number of items to return per page. Defaults to 20. The maximum number of items per page is 100.

  • max_results (int | None) – The maximum number of total results to return. When this parameter is set to None, all results are returned. Defaults to None.

Return type

HTTPAsyncIterator[Clip]

Raises
  • ValueError – Only one of game_id or clip_ids can be provided.

  • ValueError – You must provide either a game_id or clip_ids.

await .fetch_drop_entitlements(...) -> list[T]
async for item in .fetch_drop_entitlements(...):

async
fetch_drop_entitlements(*, token_for: str | PartialUser | None = None, ids: list[str] | None = None, user_id: str | int | PartialUser | None = None, game_id: str | None = None, fulfillment_status: Literal['CLAIMED', 'FULFILLED'] | None = None, first: int = 20, max_results: int | None = None) HTTPAsyncIterator[Entitlement]

This function returns a HTTPAsyncIterator

Fetches an organization’s list of entitlements that have been granted to a game, a user, or both.

Note

Entitlements returned in the response body data are not guaranteed to be sorted by any field returned by the API.

To retrieve CLAIMED or FULFILLED entitlements, use the fulfillment_status query parameter to filter results. To retrieve entitlements for a specific game, use the game_id query parameter to filter results.

Note

Requires an app access token or user access token. The Client-ID associated with the token must own the game.

Access token type

Parameter

Description

App

None

If you don’t specify request parameters, the request returns all entitlements that your organization owns.

App

user_id

The request returns all entitlements for any game that the organization granted to the specified user.

App

user_id, game_id

The request returns all entitlements that the specified game granted to the specified user.

App

game_id

The request returns all entitlements that the specified game granted to all entitled users.

User

None

If you don’t specify request parameters, the request returns all entitlements for any game that the organization granted to the user identified in the access token.

User

user_id

Invalid.

User

user_id, game_id

Invalid.

User

game_id

The request returns all entitlements that the specified game granted to the user identified in the access token.

Parameters
  • token_for (str | PartialUser | None) –

    An optional User-ID that will be used to find an appropriate managed user token for this request. The Client-ID associated with the token must own the game.

    See: add_token() to add managed tokens to the client. If this paramter is not provided or None, the default app token is used.

  • ids (list[str] | None) – A list of entitlement ids that identifies the entitlements to fetch.

  • user_id (str | int | PartialUser | None) – An optional User ID of the user that was granted entitlements.

  • game_id (str | None) – An ID that identifies a game that offered entitlements.

  • fulfillment_status (Literal["CLAIMED", "FULFILLED"] | None) – The entitlement’s fulfillment status. Used to filter the list to only those with the specified status. Possible values are: CLAIMED and FULFILLED.

  • first (int) – The maximum number of items to return per page. Defaults to 20. The maximum number of items per page is 100.

  • max_results (int | None) – The maximum number of total results to return. When this parameter is set to None, all results are returned. Defaults to None.

Return type

HTTPAsyncIterator[twitchio.Entitlement]

Raises

ValueError – You may only specifiy a maximum of 100 ids.

async fetch_emote_sets(emote_set_ids: list[str], *, token_for: str | twitchio.user.PartialUser | None = None) list[twitchio.models.chat.EmoteSet]

This function is a coroutine.

Fetches emotes for one or more specified emote sets.

Note

An emote set groups emotes that have a similar context. For example, Twitch places all the subscriber emotes that a broadcaster uploads for their channel in the same emote set.

Parameters
  • emote_set_ids (list[str]) – A list of the IDs that identifies the emote set to get. You may specify a maximum of 25 IDs.

  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

Returns

A list of EmoteSet objects.

Return type

list[EmoteSet]

Raises

ValueError – You can only specify a maximum of 25 emote set IDs.

async fetch_emotes(*, token_for: str | twitchio.user.PartialUser | None = None) list[twitchio.models.chat.GlobalEmote]

This function is a coroutine.

Fetches global emotes from the Twitch API.

Note

If you wish to fetch a specific broadcaster’s chat emotes use fetch_channel_emotes().

Parameters

token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

Returns

A list of GlobalEmote objects.

Return type

list[twitchio.GlobalEmote]

async fetch_eventsub_subscriptions(*, token_for: str | PartialUser | None = None, type: str | None = None, user_id: str | PartialUser | None = None, status: Literal['enabled', 'webhook_callback_verification_pending', 'webhook_callback_verification_failed', 'notification_failures_exceeded', 'authorization_revoked', 'moderator_removed', 'user_removed', 'version_removed', 'beta_maintenance', 'websocket_disconnected', 'websocket_failed_ping_pong', 'websocket_received_inbound_traffic', 'websocket_connection_unused', 'websocket_internal_error', 'websocket_network_timeout', 'websocket_network_error'] | None = None, max_results: int | None = None) EventsubSubscriptions

This function is a coroutine.

Fetches Eventsub Subscriptions for either webhook or websocket.

Note

type, status and user_id are mutually exclusive and only one can be passed, otherwise ValueError will be raised.

Parameters
  • token_for (str | PartialUser | None) –

    By default, if this is ignored or set to None then the App Token is used. This is the case when you want to fetch webhook events.

    Provide a user ID here for when you want to fetch websocket events tied to a user.

  • type (str | None) – Filter subscriptions by subscription type. e.g. channel.follow For a list of subscription types, see Subscription Types.

  • user_id (str | PartialUser | None) – Filter subscriptions by user ID, or PartialUser. The response contains subscriptions where this ID matches a user ID that you specified in the Condition object when you created the subscription.

  • status (str | None = None) –

    Filter subscriptions by its status. Possible values are:

    Status

    Description

    enabled

    The subscription is enabled.

    webhook_callback_verification_pending

    The subscription is pending verification of the specified callback URL.

    webhook_callback_verification_failed

    The specified callback URL failed verification.

    notification_failures_exceeded

    The notification delivery failure rate was too high.

    authorization_revoked

    The authorization was revoked for one or more users specified in the Condition object.

    moderator_removed

    The moderator that authorized the subscription is no longer one of the broadcaster’s moderators.

    user_removed

    One of the users specified in the Condition object was removed.

    chat_user_banned

    The user specified in the Condition object was banned from the broadcaster’s chat.

    version_removed

    The subscription to subscription type and version is no longer supported.

    beta_maintenance

    The subscription to the beta subscription type was removed due to maintenance.

    websocket_disconnected

    The client closed the connection.

    websocket_failed_ping_pong

    The client failed to respond to a ping message.

    websocket_received_inbound_traffic

    The client sent a non-pong message. Clients may only send pong messages (and only in response to a ping message).

    websocket_connection_unused

    The client failed to subscribe to events within the required time.

    websocket_internal_error

    The Twitch WebSocket server experienced an unexpected error.

    websocket_network_timeout

    The Twitch WebSocket server timed out writing the message to the client.

    websocket_network_error

    The Twitch WebSocket server experienced a network error writing the message to the client.

    websocket_failed_to_reconnect

    The client failed to reconnect to the Twitch WebSocket server within the required time after a Reconnect Message.

  • max_results (int | None) – The maximum number of total results to return. When this parameter is set to None, all results are returned. Defaults to None.

Return type

EventsubSubscriptions

Raises

ValueError – Only one of ‘status’, ‘user_id’, or ‘type’ can be provided.

await .fetch_extension_transactions(...) -> list[T]
async for item in .fetch_extension_transactions(...):

async
fetch_extension_transactions(extension_id: str, *, ids: list[str] | None = None, first: int = 20, max_results: int | None = None) HTTPAsyncIterator[ExtensionTransaction]

This function returns a HTTPAsyncIterator

Fetches global emotes from the Twitch API.

Note

The ID in the extension_id parameter must match the Client-ID provided to this Client.

Parameters
  • extension_id (str) – The ID of the extension whose list of transactions you want to fetch.

  • ids (list[str] | None) – A transaction ID used to filter the list of transactions.

  • first (int) – The maximum number of items to return per page. Defaults to 20. The maximum number of items per page is 100.

  • max_results (int | None) – The maximum number of total results to return. When this parameter is set to None, all results are returned. Defaults to None.

Return type

HTTPAsyncIterator[ExtensionTransaction]

async fetch_extensions(*, token_for: str | twitchio.user.PartialUser) list[twitchio.user.Extension]

This function is a coroutine.

Fetch a list of all extensions (both active and inactive) that the broadcaster has installed.

The user ID in the access token identifies the broadcaster.

Note

Requires a user access token that includes the user:read:broadcast or user:edit:broadcast scope. To include inactive extensions, you must include the user:edit:broadcast scope.

Parameters

token_for (str | PartialUser) –

The User ID, or PartialUser, that will be used to find an appropriate managed user token for this request. The token must inlcude the user:read:broadcast or user:edit:broadcast scope.

See: add_token() to add managed tokens to the client. To include inactive extensions, you must include the user:edit:broadcast scope.

Returns

List of UserExtension objects.

Return type

list[UserExtension]

async fetch_game(*, name: str | None = None, id: str | None = None, igdb_id: str | None = None, token_for: str | twitchio.user.PartialUser | None = None) twitchio.models.games.Game | None

This function is a coroutine.

Fetch a Game object with the provided name, id, or igdb_id.

One of name, id, or igdb_id must be provided. If more than one is provided or no parameters are provided, a ValueError will be raised.

If no game is found, None will be returned.

Note

See: fetch_games() to fetch multiple games at once.

See: fetch_top_games() to fetch the top games currently being streamed.

Parameters
  • name (str | None) – The name of the game to fetch.

  • id (str | None) – The id of the game to fetch.

  • igdb_id (str | None) – The igdb id of the game to fetch.

  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

Returns

The twitchio.Game object if found, otherwise None.

Return type

Game | None

Raises
  • ValueError – Only one of the name, id, or igdb_id parameters can be provided.

  • ValueError – One of the name, id, or igdb_id parameters must be provided.

async fetch_games(*, names: list[str] | None = None, ids: list[str] | None = None, igdb_ids: list[str] | None = None, token_for: str | twitchio.user.PartialUser | None = None) list[twitchio.models.games.Game]

This function is a coroutine.

Fetches information about multiple games on Twitch.

Parameters
  • names (list[str] | None) – A list of game names to use to fetch information about. Defaults to None.

  • ids (list[str] | None) – A list of game ids to use to fetch information about. Defaults to None.

  • igdb_ids (list[str] | None) – A list of igdb ids to use to fetch information about. Defaults to None.

  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

Returns

A list of twitchio.Game objects.

Return type

list[twitchio.Game]

await .fetch_stream_markers(...) -> list[T]
async for item in .fetch_stream_markers(...):

async
fetch_stream_markers(*, video_id: str, token_for: str | PartialUser, first: int = 20, max_results: int | None = None) HTTPAsyncIterator[VideoMarkers]

This function returns a HTTPAsyncIterator

Fetches markers from a specific user’s most recent stream or from the specified VOD/video.

A marker is an arbitrary point in a live stream that the broadcaster or editor has marked, so they can return to that spot later to create video highlights.

Important

See: fetch_stream_markers() for a more streamlined version of this method.

Note

Requires a user access token that includes the user:read:broadcast or channel:manage:broadcast scope.

Parameters
  • video_id (str) – A video on demand (VOD)/video ID. The request returns the markers from this VOD/video. The User ID provided to token_for must own the video or the user must be one of the broadcaster’s editors.

  • token_for (str | PartialUser) –

    The User ID, or PartialUser, that will be used to find an appropriate managed user token for this request. The token must inlcude the user:read:broadcast or channel:manage:broadcast scope

    See: add_token() to add managed tokens to the client.

  • first (int) – The maximum number of items to return per page. Defaults to 20. The maximum number of items per page is 100.

  • max_results (int | None) – The maximum number of total results to return. When this parameter is set to None, all results are returned. Defaults to None.

Return type

HTTPAsyncIterator[twitchio.VideoMarkers]

await .fetch_streams(...) -> list[T]
async for item in .fetch_streams(...):

async
fetch_streams(*, user_ids: list[int | str] | None = None, game_ids: list[int | str] | None = None, user_logins: list[int | str] | None = None, languages: list[str] | None = None, type: Literal['all', 'live'] = 'all', token_for: str | PartialUser | None = None, first: int = 20, max_results: int | None = None) HTTPAsyncIterator[Stream]

This function returns a HTTPAsyncIterator

Fetches streams from the Twitch API.

Parameters
  • user_ids (list[int | str] | None) – An optional list of User-IDs to fetch live stream information for.

  • game_ids (list[int | str] | None) – An optional list of Game-IDs to fetch live streams for.

  • user_logins (list[str] | None) – An optional list of User-Logins to fetch live stream information for.

  • languages (list[str] | None) – A language code used to filter the list of streams. Returns only streams that broadcast in the specified language. Specify the language using an ISO 639-1 two-letter language code or other if the broadcast uses a language not in the list of supported stream languages. You may specify a maximum of 100 language codes.

  • type (Literal["all", "live"]) –

    One of “all” or “live”. Defaults to “all”. Specifies what type of stream to fetch.

    Important

    Twitch deprecated filtering streams by type. all and live both return the same data. This is being kept in the library in case of future additions.

  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

  • first (int) – The maximum number of items to return per page. Defaults to 20. The maximum number of items per page is 100.

  • max_results (int | None) – The maximum number of total results to return. When this parameter is set to None, all results are returned. Defaults to None.

Return type

HTTPAsyncIterator[twitchio.Stream]

async fetch_team(*, team_name: str | None = None, team_id: str | None = None, token_for: str | twitchio.user.PartialUser | None = None) Team

This function is a coroutine.

Fetches information about a specific Twitch team.

You must provide one of either team_name or team_id.

Parameters
  • team_name (str | None) – The team name.

  • team_id (str | None) – The team id.

  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

Returns

The twitchio.Team object.

Return type

Team

Raises

ValueError – You can only provide either team_name or team_id, not both.

await .fetch_top_games(...) -> list[T]
async for item in .fetch_top_games(...):

async
fetch_top_games(*, token_for: str | twitchio.user.PartialUser | None = None, first: int = 20, max_results: int | None = None) HTTPAsyncIterator[Game]

This function returns a HTTPAsyncIterator

Fetches information about the current top games on Twitch.

Parameters
  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

  • first (int) – The maximum number of items to return per page. Defaults to 20. The maximum number of items per page is 100.

  • max_results (int | None) – The maximum number of total results to return. When this parameter is set to None, all results are returned. Defaults to None.

Return type

HTTPAsyncIterator[twitchio.Game]

async fetch_users(*, ids: list[str | int] | None = None, logins: list[str] | None = None, token_for: str | twitchio.user.PartialUser | None = None) list[twitchio.user.User]

This function is a coroutine.

Fetch information about one or more users.

Note

You may look up users using their user ID, login name, or both but the sum total of the number of users you may look up is 100.

For example, you may specify 50 IDs and 50 names or 100 IDs or names, but you cannot specify 100 IDs and 100 names.

If you don’t specify IDs or login names but provide the token_for parameter, the request returns information about the user associated with the access token.

To include the user’s verified email address in the response, you must have a user access token that includes the user:read:email scope.

Parameters
  • ids (list[str | int] | None) – The ids of the users to fetch information about.

  • logins (list[str] | None) – The login names of the users to fetch information about.

  • token_for (str | PartialUser | None) –

    An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

    If this parameter is provided, the token must have the user:read:email scope in order to request the user’s verified email address.

Returns

A list of twitchio.User objects.

Return type

list[twitchio.User]

Raises

ValueError – The combined number of ‘ids’ and ‘logins’ must not exceed 100 elements.

await .fetch_videos(...) -> list[T]
async for item in .fetch_videos(...):

async
fetch_videos(*, ids: list[str | int] | None = None, user_id: str | int | PartialUser | None = None, game_id: str | int | None = None, language: str | None = None, period: Literal['all', 'day', 'month', 'week'] = 'all', sort: Literal['time', 'trending', 'views'] = 'time', type: Literal['all', 'archive', 'highlight', 'upload'] = 'all', first: int = 20, max_results: int | None = None, token_for: str | PartialUser | None = None) HTTPAsyncIterator[Video]

This function returns a HTTPAsyncIterator

Fetch a list of Video objects with the provided ids, user_id or game_id.

One of ids, user_id or game_id must be provided. If more than one is provided or no parameters are provided, a ValueError will be raised.

Parameters
  • ids (list[str | int] | None) – A list of video IDs to fetch.

  • user_id (str | int | PartialUser | None) – The ID of the user whose list of videos you want to fetch.

  • game_id (str | int | None) – The igdb id of the game to fetch.

  • language (str | None) –

    A filter used to filter the list of videos by the language that the video owner broadcasts in.

    For example, to get videos that were broadcast in German, set this parameter to the ISO 639-1 two-letter code for German (i.e., DE).

    For a list of supported languages, see Supported Stream Language. If the language is not supported, use other.

    Note

    Specify this parameter only if you specify the game_id query parameter.

  • period (Literal["all", "day", "month", "week"]) –

    A filter used to filter the list of videos by when they were published. For example, videos published in the last week. Possible values are: all, day, month, week.

    The default is all, which returns videos published in all periods.

    Note

    Specify this parameter only if you specify the game_id or user_id query parameter.

  • sort (Literal["time", "trending", "views"]) –

    The order to sort the returned videos in.

    Sort Key

    Description

    time

    Sort the results in descending order by when they were created (i.e., latest video first).

    trending

    Sort the results in descending order by biggest gains in viewership (i.e., highest trending video first).

    views

    Sort the results in descending order by most views (i.e., highest number of views first).

    The default is time.

    Note

    Specify this parameter only if you specify the game_id or user_id query parameter.

  • type (Literal["all", "archive", "highlight", "upload"]) –

    A filter used to filter the list of videos by the video’s type.

    Type

    Description

    all

    Include all video types.

    archive

    On-demand videos (VODs) of past streams.

    highlight

    Highlight reels of past streams.

    upload

    External videos that the broadcaster uploaded using the Video Producer.

    The default is all, which returns all video types.

    Note

    Specify this parameter only if you specify the game_id or user_id query parameter.

  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

  • first (int) – The maximum number of items to return per page. Defaults to 20. The maximum number of items per page is 100.

  • max_results (int | None) – The maximum number of total results to return. When this parameter is set to None, all results are returned. Defaults to None.

Return type

HTTPAsyncIterator[twitchio.Video]

Raises
  • ValueError – Only one of the ‘ids’, ‘user_id’, or ‘game_id’ parameters can be provided.

  • ValueError – One of the ‘ids’, ‘user_id’, or ‘game_id’ parameters must be provided.

get_command(name: str, /) Optional[Union[Command[Component_T, ...], Group[Any, ...]]]

Method which returns a previously added Command or Group.

If a Command or Group can not be found, has been removed or has not been added, this method will return None.

Parameters

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

Returns

  • Command | Group – The command or group command with the provided name or alias associated with this Mixin.

  • None – A command or group with the provided name or alias could not be found.

@ listen(name: str | None = None) Any

This function is a decorator.

A decorator that adds a coroutine as an event listener.

Listeners listen for dispatched events on the Client or Bot and can come from multiple sources, such as internally, or via EventSub. Unlike the overridable events built into bot Client and Bot, listeners do not change the default functionality of the event, and can be used as many times as required.

By default, listeners use the name of the function wrapped for the event name. This can be changed by passing the name parameter.

For a list of events and their documentation, see: Events Reference.

For adding listeners to components, see: listener()

Examples

@bot.listen()
async def event_message(message: twitchio.ChatMessage) -> None:
    ...

# You can have multiple of the same event...
@bot.listen("event_message")
async def event_message_two(message: twitchio.ChatMessage) -> None:
    ...
Parameters

name (str) – The name of the event to listen to, E.g. "event_message" or simply "message".

async load_tokens(path: str | None = None, /) None

This function is a coroutine.

Method used to load tokens when the Client starts.

Note

This method is called by the client during login() but before setup_hook() when the load_tokens keyword-argument is True in either, run(), start() or login() (Default).

You can override this method to implement your own token loading logic into the client, such as from a database.

By default this method loads tokens from a file named “.tio.tokens.json” if it is present; always present if you use the default method of saving tokens.

However, it is preferred you would override this function to load your tokens from a database, as this has far less chance of being corrupted, damaged or lost.

Parameters

path (str | None) – The path to load tokens from, if this is None and the method has not been overriden, this will default to .tio.tokens.json. Defaults to None.

Examples

class Client(twitchio.Client):

    async def load_tokens(self, path: str | None = None) -> None:
        # Code to fetch all tokens from the database here...
        ...

        for row in tokens:
            await self.add_token(row["token"], row["refresh"])
async login(*, token: str | None = None, load_tokens: bool = True, save_tokens: bool = True) None

This function is a coroutine.

Method to login the client and generate or store an app token.

This method is called automatically when using start(). You should NOT call this method if you are using start().

This method calls setup_hook().

Note

If no token is provided, the client will attempt to generate a new app token for you. This is usually preferred as generating a token is inexpensive and does not have rate-limits associated with it.

Parameters
  • token (str | None) – An optional app token to use instead of generating one automatically.

  • load_tokens (bool) – Optional bool which indicates whether the Client should call load_tokens() during login automatically. Defaults to True.

  • save_tokens (bool) – Optional bool which inicates whether the Client should call save_tokens() during the close() automatically. Defaults to True.

remove_command(name: str, /) Optional[Command[Any, ...]]

Remove a Command object from the mixin by it’s name.

Parameters

name (str) – The name of the Command to remove that was previously added.

Returns

  • None – No commands with provided name were found.

  • Command – The Command which was removed.

remove_listener(listener: Callable[..., Coroutine[Any, Any, None]]) Callable[..., Coroutine[Any, Any, None]] | None

Method to remove a currently registered listener from the client.

Parameters

listener (Callable[..., Coroutine[Any, Any, None]]) – The coroutine wrapped with listen() or added via add_listener() to remove as a listener.

Returns

  • Callable[…, Coroutine[Any, Any, None]] – If a listener was removed, the coroutine function will be returned.

  • None – Returns None when no listener was removed.

async remove_token(user_id: str, /) TokenMappingData | None

This function is a coroutine.

Removes a token for the specified user-ID from the Client.

Removing a token will ensure the client stops managing the token.

This method has been made async for convenience when overriding the default functionality.

You can override this method to implement custom logic, such as removing a token from your database.

Parameters

user_id (str) – The user-ID for the token to remove from the client. This argument is positional-only.

Returns

  • TokenMappingData – The token data assoicated with the user-id that was successfully removed.

  • None – The user-id was not managed by the client.

run(token: str | None = None, *, with_adapter: bool = True, load_tokens: bool = True, save_tokens: bool = True) None

Method to login the client and create a continuously running event loop.

The behaviour of this method is similar to start() but instead of being used in an already running async environment, this method will setup and create an async environment for you.

You should not call login() if you are using this method as it is called internally for you.

Important

You can not use this method in an already running async event loop. See: start() for starting the client in already running async environments.

Note

This method will block until the client is closed.

Parameters
  • token (str | None) – An optional app token to use instead of generating one automatically.

  • with_adapter (bool) – Whether to start and run a web adapter. Defaults to True. See: … for more information.

  • load_tokens (bool) – Optional bool which indicates whether the Client should call load_tokens() during login() automatically. Defaults to True.

  • save_tokens (bool) – Optional bool which inicates whether the Client should call save_tokens() during the close() automatically. Defaults to True.

Examples

client = twitchio.Client(...)
client.run()
async save_tokens(path: str | None = None, /) None

This function is a coroutine.

Method which saves all the added OAuth tokens currently managed by this Client.

Note

This method is called by the client when it is gracefully closed and the save_tokens keyword-argument is True in either, run(), start() or login() (Default).

Note

By default this method saves to a JSON file named “.tio.tokens.json”.

You can override this method to implement your own custom logic, such as saving tokens to a database, however it is preferred to use add_token() to ensure the tokens are handled as they are added.

Parameters

path (str | None) – The path of the file to save to. Defaults to .tio.tokens.json.

await .search_categories(...) -> list[T]
async for item in .search_categories(...):

async
search_categories(query: str, *, token_for: str | twitchio.user.PartialUser | None = None, first: int = 20, max_results: int | None = None) HTTPAsyncIterator[Game]

This function returns a HTTPAsyncIterator

Searches Twitch categories via the API.

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

  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

  • first (int) – The maximum number of items to return per page. Defaults to 20. The maximum number of items per page is 100.

  • max_results (int | None) – The maximum number of total results to return. When this parameter is set to None, all results are returned. Defaults to None.

Return type

HTTPAsyncIterator[twitchio.Game]

await .search_channels(...) -> list[T]
async for item in .search_channels(...):

async
search_channels(query: str, *, live: bool = False, token_for: str | PartialUser | None = None, first: int = 20, max_results: int | None = None) HTTPAsyncIterator[SearchChannel]

This function returns a HTTPAsyncIterator

Searches Twitch channels that match the specified query and have streamed content within the past 6 months.

Note

If the live parameter is set to False (default), the query will look to match broadcaster login names. If the live parameter is set to True, the query will match on the broadcaster login names and category names.

To match, the beginning of the broadcaster’s name or category must match the query string.

The comparison is case insensitive. If the query string is angel_of_death, it will matche all names that begin with angel_of_death.

However, if the query string is a phrase like angel of death, it will match to names starting with angelofdeath or names starting with angel_of_death.

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

  • live (bool) – Whether to return live channels only. Defaults to False.

  • token_for (str | PartialUser | None) – An optional User-ID, or PartialUser object, that will be used to find an appropriate managed user token for this request. See: add_token() to add managed tokens to the client.

  • first (int) – The maximum number of items to return per page. Defaults to 20. The maximum number of items per page is 100.

  • max_results (int | None) – The maximum number of total results to return. When this parameter is set to None, all results are returned. Defaults to None.

Return type

HTTPAsyncIterator[twitchio.SearchChannel]

async setup_hook() None

Method called after login() has been called but before the client is ready.

start() calls login() internally for you, so when using start() this method will be called after the client has generated and validated an app token. The client won’t complete start up until this method has completed.

This method is intended to be overriden to provide an async environment for any setup required.

By default, this method does not implement any logic.

async start(token: str | None = None, *, with_adapter: bool = True, load_tokens: bool = True, save_tokens: bool = True) None

This function is a coroutine.

Method to login and run the Client asynchronously on an already running event loop.

You should not call login() if you are using this method as it is called internally for you.

Note

This method blocks asynchronously until the client is closed.

Parameters
  • token (str | None) – An optional app token to use instead of generating one automatically.

  • with_adapter (bool) – Whether to start and run a web adapter. Defaults to True. See: … for more information.

  • load_tokens (bool) – Optional bool which indicates whether the Client should call load_tokens() during login() automatically. Defaults to True.

  • save_tokens (bool) – Optional bool which inicates whether the Client should call save_tokens() during the close() automatically. Defaults to True.

Examples

import asyncio
import twitchio

async def main() -> None:
    client = twitchio.Client(...)

    async with client:
        await client.start()
property tokens: MappingProxyType[str, TokenMappingData]

Property which returns a read-only mapping of the tokens that are managed by the Client.

For various methods of managing the tokens on the client, see:

add_token()

remove_token()

load_tokens()

save_tokens()

Warning

This method returns sensitive information such as user-tokens. You should take care not to expose these tokens.

property unique_commands: set[Union[twitchio.ext.commands.core.Command[Component_T, ...], twitchio.ext.commands.core.Group[Any, ...]]]

Property returning a set of currently added Command and Group associated with this Mixin.

async update_entitlements(*, ids: list[str] | None = None, fulfillment_status: Literal['CLAIMED', 'FULFILLED'] | None = None, token_for: str | PartialUser | None = None) list[EntitlementStatus]

This function is a coroutine.

Updates a Drop entitlement’s fulfillment status.

Note

Requires an app access token or user access token. The Client-ID associated with the token must own the game associated with this drop entitlment.

Access token type

Updated Data

App

Updates all entitlements with benefits owned by the organization in the access token.

User

Updates all entitlements owned by the user in the access win the access token and where the benefits are owned by the organization in the access token.

Parameters
  • ids (list[str] | None) – A list of IDs that identify the entitlements to update. You may specify a maximum of 100 IDs.

  • fulfillment_status (Literal[""CLAIMED", "FULFILLED"] | None) – The fulfillment status to set the entitlements to. Possible values are: CLAIMED and FULFILLED.

  • token_for (str | PartialUser | None) –

    An optional User ID that will be used to find an appropriate managed user token for this request. The Client-ID associated with the token must own the game associated with this drop entitlment.

    See: add_token() to add managed tokens to the client. If this paramter is not provided or None, the default app token is used.

Returns

A list of twitchio.EntitlementStatus objects.

Return type

list[twitchio.EntitlementStatus]

Raises

ValueError – You may only specifiy a maximum of 100 ids.

async update_extensions(*, user_extensions: ActiveExtensions, token_for: str | twitchio.user.PartialUser) ActiveExtensions

This function is a coroutine.

Update an installed extension’s information for a specific broadcaster.

You can update the extension’s activation state, ID, and version number. The User-ID passed to token_for identifies the broadcaster whose extensions you are updating.

Note

The best way to change an installed extension’s configuration is to use fetch_active_extensions() to fetch the extension.

You can then edit the approperiate extension within the ActiveExtensions model and pass it to this method.

Note

Requires a user access token that includes the user:edit:broadcast scope. See: add_token() to add managed tokens to the client.

Parameters

token_for (str | PartialUser) –

The User ID, or PartialUser, that will be used to find an appropriate managed user token for this request. The token must inlcude the user:edit:broadcast scope.

See: add_token() to add managed tokens to the client.

Returns

The ActiveExtensions object.

Return type

ActiveExtensions

property user: twitchio.user.User | twitchio.user.PartialUser | None

Property which returns the User or PartialUser associated with with the Client/Bot.

In most cases this will be a User object. Could be PartialUser when passing False to the fetch_client_user keyword parameter of Client.

Could be None if no bot_id was passed to the Client constructor.

Important

If bot_id has not been passed to the constructor of Client this will return None.

async wait_for(event: str, *, timeout: float | None = None, predicate: WaitPredicateT | None = None) Any

This function is a coroutine.

Method which waits for any known dispatched event and returns the payload associated with the event.

This method can be used with a predicate check to determine whether the wait_for should stop listening and return the event payload.

Parameters
  • event (str) –

    The name of the event/listener to wait for. This should be the name of the event minus the event_ prefix.

    E.g. chat_message

  • timeout (float | None) –

    An optional float to pass that this method will wait for a valid event. If None wait_for won’t timeout. Defaults to None.

    If this method does timeout, the TimeoutError will be raised and propagated back.

  • predicate (WaitPredicateT) –

    An optional coroutine to use as a check to determine whether this method should stop listening and return the event payload. This coroutine should always return a bool.

    The predicate function should take in the same payload as the event you are waiting for.

Examples

async def predicate(payload: twitchio.ChatMessage) -> bool:
    # Only wait for a message sent by "chillymosh"
    return payload.chatter.name == "chillymosh"

payload: twitchio.ChatMessage = await client.wait_for("chat_message", predicate=predicate)
print(f"Chillymosh said: {payload.text}")
Raises

TimeoutError – Raised when waiting for an event that meets the requirements and passes the predicate check exceeds the timeout.

Returns

The payload associated with the event being listened to.

Return type

Any

async wait_until_ready() None

This function is a coroutine.

Method which suspends the current coroutine and waits for “event_ready” to be dispatched.

If “event_ready” has previously been dispatched, this method returns immediately.

“event_ready” is dispatched after the HTTP Client has successfully logged in, tokens have sucessfully been loaded, and setup_hook() has completed execution.

Warning

Since this method directly relies on setup_hook() completing, using it in setup_hook() or in any call setup_hook() is waiting for execution to complete, will completely deadlock the Client.

Mixin

class twitchio.ext.commands.Mixin(*args: Any, **kwargs: Any)
property case_insensitive: bool

Property returning a bool indicating whether this Mixin is using case insensitive commands.

property commands: dict[str, Union[twitchio.ext.commands.core.Command[Component_T, ...], twitchio.ext.commands.core.Group[Any, ...]]]

Property returning the mapping of currently added Command and Group associated with this Mixin.

This mapping includes aliases as keys.

Note

See: unique_commands for a set of commands without duplicates due to aliases.

property unique_commands: set[Union[twitchio.ext.commands.core.Command[Component_T, ...], twitchio.ext.commands.core.Group[Any, ...]]]

Property returning a set of currently added Command and Group associated with this Mixin.

get_command(name: str, /) Optional[Union[Command[Component_T, ...], Group[Any, ...]]]

Method which returns a previously added Command or Group.

If a Command or Group can not be found, has been removed or has not been added, this method will return None.

Parameters

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

Returns

  • Command | Group – The command or group command with the provided name or alias associated with this Mixin.

  • None – A command or group with the provided name or alias could not be found.

add_command(command: Command[Component_T, ...], /) None

Add a Command object to the mixin.

For group commands you would usually use the command() decorator instead.

See: command().

remove_command(name: str, /) Optional[Command[Any, ...]]

Remove a Command object from the mixin by it’s name.

Parameters

name (str) – The name of the Command to remove that was previously added.

Returns

  • None – No commands with provided name were found.

  • Command – The Command which was removed.