AutoClient

class twitchio.AutoClient(*, client_id: str, client_secret: str, bot_id: str | None = None, **kwargs: Unpack[AutoClientOptions])

The TwitchIO AutoClient class used to easily manage Twitch Conduits and Shards.

There is a commands.ext version of this class named AutoBot which inherits from twitchio.ext.commands.Bot instead of Client.

This class inherits from Client and as such most attributes, properties and methods from Client are also available.

This or AutoBot are the preferred clients of use when your application is either in multiple channels/broadcasters or requires subscription continuity.

Twitch Conduits are a method of EventSub transport which allow higher throughput of events, higher (essentially unlimited) subscription limts (within cost), continutiy of subscriptions and scaling.

To benefit from the subscription continuity of Conduits, your application is expected to have been connected to the associated Conduit within 72 hours of it going offline.

This and the AutoBot classes make it easier to manage Conduits by implementing logic to aid in connection, shard association and conduit/shard scaling. There are a few common ways they can be setup, with the main 3 cases showcased below.

The most common usecase will be case 1, which allows an application to connect to a new or existing Conduit automatically with little intervention or setup from developers, in this case the following happens:

  • If excactly 1 Conduit exists:
    • Your application will associate with that conduit and assign transports; existing subscriptions remain.

  • If no Conduit exists:
    • Your application will create and associate itself with the new Conduit, assigning transports and subscribing.

  • By default the amount of shards will be equal len(subscriptions) / max_per_shard or 2 whichever is greater or len(shard_ids) if passed.
    • Most applications will only require 2 or 3 shards, with the second shard mostly existing as a fallback.

In both scenarios above your application can restart at anytime without re-subscribing, however take note of the following requirements.

  • Your application must reconnect within 72 hours.
    • If 72 hours passes; your application will need to resubscribe to any eventsub subscriptions.

    • This will be done automatically if subscriptions are passed to the constructor.

  • Your application should be the only instance running. For multiple instances see case 2 and 3.

  • If you require new subscriptions since the application was restarted, they can be passed to multi_subscribe() in something like setup_hook().

An example of case 1:

class Bot(commands.AutoBot):

    def __init__(self, subs: list[twitchio.eventsub.SubscriptionPayload], *args, **kwargs) -> None:
        super().__init__(*args, **kwargs, subscriptions=subs)

    async def event_message(self, payload: twitchio.ChatMessage) -> None:
        print(f"Received Message: {payload}")


async def main() -> None:
    # An example list of subscriptions; you could create this list however you need, e.g. from a database...
    # Subscribe to 3 channels messages...
    # If you require additional subscriptions after restart and 72 hours HAS NOT passed; See: multi_subscribe()

    subs = [
        eventsub.ChatMessageSubscription(broadcaster_user_id=..., user_id=...),
        eventsub.ChatMessageSubscription(broadcaster_user_id=..., user_id=...),
        eventsub.ChatMessageSubscription(broadcaster_user_id=..., user_id=...),
    ]

    async with Bot(subs=subs, client_id=..., client_secret=..., bot_id=..., prefix=...) as bot:
        await bot.start()

Case 2 is another common scenario which allows developers to connect to a specific Conduit by providing the Conduit-ID.

In this case the following happens:

  • Your application will connect to the provided Conduit-ID.
    • If the conduit does not exist or could not be found, an error will be raised on start-up.

    • Your application will assign the amount of transports equal to the shard count the Conduit returns from Twitch or the amount passed to len(shard_ids).

    • shard_ids is not a required parameter, however see below for more info.

This case allows greater control over which Conduit your application connects to which is mostly only useful if your setup includes multiple Conduits and/or multiple instances of AutoClient or AutoBot.

If the former is true, each instance of AutoClient and AutoBot should realistically connect to a different conduit each.

When the latter is true, your application can be setup to effectively distribute shards equally accross instances by connecting to the same Conduit. In this scenario you will also need to pass the shard_ids parameter to each instance, making sure each instance is assigned shards. E.g. shard_ids=[0, 1, 2] and shard_ids=[3, 4, 5] for a 2 instance setup on a Conduit which contains 6 shards.

As this case is more involved and requires much more attention; e.g. multiple instances need to be started correctly and connections to multiple Conduits need to be properly configured it usually wouldn’t be advised for small to medium sized applications, suiting only larger applications that require some scaling outside of a single process.

A single AutoClient (hardware permitting) should be able to handle a large amount of subscriptions before needing to be scaled.

An example of case 2 (multiple instances on one conduit):

In this scenario your conduit should have 6 shards associated with it already. You should do this before starting multiple instances. The example below would simply be run twice, assigning 3 shards to each instance, E.g. on the first instance shard_ids=[0, 1, 2] and the second instance shard_ids=[3, 4, 5].

You can prepare for this scenario by calling twitchio.Conduit.update() on the appropriate Conduit or by calling update_shard_count() with 6 shards, and keeping note of the Conduit-ID, before starting both processes.

class Bot(commands.AutoBot):

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(
            *args,
            **kwargs,
            subscriptions=subs,
            conduit_id="CONDUIT_1_ID",
            shard_ids=[...],
        )

    async def event_message(self, payload: twitchio.ChatMessage) -> None:
        print(f"Received Message: {payload}")


async def main() -> None:
    async with Bot(client_id=..., client_secret=..., bot_id=..., prefix=...) as bot:
        await bot.start()

For case 2 when connecting to multiple conduits instead, most of the above documentation applies, however you should make sure to provide a different conduit_id per instance.

Case 3 is the least obvious and likely the least required. In this case if the conduit_id parameter is passed True, the AutoClient will create and start a new Conduit regardless of whether your application currently has a Conduit(s) existing on the API. Mostly for this scenario it could be used to quickly create a new Conduit to be used with Case 2 directly after.

To scale up or down a single instance of AutoClient see: update_shard_count().

See: ConduitInfo and conduit_info for the class used to manage the Conduit on the application.

For more information on Conduits, please see: Twitch Docs

Parameters
  • conduit_id (str | bool | None) – An optional parameter passed, which could be the ID of the Conduit as a str you want this instance to take ownership of, or None to connect to an existing Conduit or create one if none exist. You can also pass True to this parameter, however see above for more details and examples on how this parameter affects your application. Defaults to None, which is the most common use case.

  • shard_ids (list[int]) – An optional list of int which sets the shard IDs this instance of AutoClient will assign transports for. If the AutoClient creates a new Conduit the length of this parameter will be the shard_count which the Conduit will be created with. This parameter can be used to equally distribute shards accross multiple instances/processes on a single Conduit. You should make sure the list of shard_ids is consecutive and in order. E.g. list(range(3)) or [0, 1, 2]. Shard ID’s are 0 indexed.

  • max_per_shard (int) – An optional parameter which allows the Client to automatically determine the amount of shards you may require based on the amount of subscriptions passed. The default value is 1000 and the algorithm used to determine shards is simply: len(subscriptons) / max_per_shard or 2 whichever is greater. Note this parameter has no effect when shard_ids is explicitly passed.

  • subscriptions (list[twitchio.eventsub.SubscriptionPayload]) – An optional list of any combination of EventSub subscriptions (all of which inherit from SubscriptionPayload) the Client should attempt to subscribe to when required. The AutoClient will only attempt to subscribe to these subscriptions when it creates a new Conduit. If your Client connects to an existing Conduit either by passing conduit_id or automatically, this parameter has no effect. In cases where you need to update an existing Conduit with new subscriptions see: multi_subscribe() or the parameter force_subscribe.

  • force_subscribe (bool) – An optional bool which when True will force attempt to subscribe to the subscriptions provided in the subscriptions parameter, regardless of whether a new conduit was created or not. Defaults to False.

  • force_scale (bool) – An optional bool which when True will force the Conduit associated with the AutoClient/Bot to scale up/down to the provided amount of shards in the shard_ids parameter if provided. If the shard_ids parameter is not passed, this parameter has no effect. Defaults to False.

property conduit_info: ConduitInfo

Property returning the ConduitInfo associated with the AutoClient or AutoBot.

async multi_subscribe(subscriptions: Collection[SubscriptionPayload], *, wait: Literal[True] = True, stop_on_error: bool = False) MultiSubscribePayload
async multi_subscribe(subscriptions: Collection[SubscriptionPayload], *, wait: Literal[False] = False, stop_on_error: bool = False) asyncio.Task[MultiSubscribePayload]

This function is a coroutine.

This method attempts to subscribe to the provided list of EventSub subscriptions on the Conduit associated with the AutoClient.

Since Conduits maintain subscriptions for up to 72 hours after the Conduit/Shards go offline, calling this method is intended to be used to setup the AutoClient initially, or after a Conduit has been offline for 72 hours or longer; however it can be used to subscribe at any other time.

Ideally the bulk of your subscriptions should only ever need to be subscribed to once and an Online status for the Conduit and associated shards should be maintained and/or kept within the 72 hour limit.

Conduit subscriptions only use App Access Tokens (akin to webhooks); however the user must have authorised the App (Client-ID) with the appropriate scopes associated with subscriptions.

An App Access Token is generated automatically each time the AutoClient is logged in which is called automatically with login(), start() and run().

To avoid some confusion and ease of use, if a list of subscriptions is passed to the AutoClient constructor this method will be called automatically whenever it creates a new Conduit on startup.

By default this method will not stop attempting to subscribe to subscriptions if an error is received during it’s invocation, instead any subscriptions that failed will be included in the returned payload. This behaviour can be changed by setting the stop_on_error parameter to True.

If wait=True (default) this method acts like any other coroutine used with await. Otherwise when wait=False the subscriptions will occur in a background task and you will receive the created asyncio.Task instead; when wait=False you will not receive a payload upon completion, however the task can be awaited later to receive the result.

Parameters
  • subscriptions (list[SubscriptionPayload]) – A list of SubscriptionPayload to attempt subscribing to on the associated Conduit.

  • wait (bool) – Whetheer to treat this method like a standard awaited coroutine or create and return a asyncio.Task instead. Defaults to True which treats the method as a standard coroutine.

  • stop_on_error (bool) – Whether to stop and raise an exception when an error occurs attempting to subscribe to any subscription provided. Defaults to False, which adds any errors to the returned MultiSubscribePayload instead of raising.

Returns

  • MultiSubscribePayload – The payload containing successfull subscriptions and any errors.

  • asyncio.Task – When wait is False, the created background task is returned.

Raises

MissingConduit – Cannot subscribe when no Conduit is associated with this Client.

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()
property adapter: BaseAdapter[Any]

Property returning the AiohttpAdapter or StarlettepAdapter the bot is currently running.

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 bot_id: str | None

Property which returns the User-ID associated with this Client if set, or None.

This can be set using the bot_id parameter when initialising the Client.

Note

It is highly recommended to set this parameter.

async create_conduit(shard_count: int) Conduit

This function is a coroutine.

Method to create a Conduit on the API.

Parameters

shard_count (int) – The amount of shards to assign to the Conduit. Must be between 1 and 20_000.

Raises

ValueErrorshard_count must be between 1 and 20_000.

Returns

The newly created Conduit.

Return type

Conduit

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 delete_websocket_subscription(*args: Any, **kwargs: Any) Any

Important

AutoClient does not implement this method.

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_auth_by_users(user_ids: list[str]) list[twitchio.user.UserAuthorisation]

This function is a coroutine. Fetches authentication information for one or more users, up to 10. This uses the app token associated with the Client ID and Secret provided.

Parameters

user_ids (list[str]) – A list of user IDs to fetch authentication information for. You may only fetch a maximum of 10 user IDs at a time.

Return type

list[UserAuthorisation]

Raises

ValueError – You may only fetch a maximum of 10 user IDs at a time.

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_channel(broadcaster_id: str | int, *, token_for: str | twitchio.user.PartialUser | None = None) twitchio.models.channels.ChannelInfo | None

This function is a coroutine.

Retrieve channel information from the API for a single broadcaster.

Parameters
  • broadcaster_id (str | int) – The ID of the channel you wish to receive information 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

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]

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.

async fetch_conduit(conduit_id: str) twitchio.models.eventsub_.Conduit | None

This function is a coroutine.

Method which retrieves a Conduit from the API, with the provided ID.

Parameters

conduit_id (str) – The ID of the Conduit to retrieve.

Returns

  • Conduit – The Conduit with the associated ID, if found.

  • None – If the Conduit cannnot be found None is returned.

async fetch_conduits() list[twitchio.models.eventsub_.Conduit]

This function is a coroutine.

Method to retrieve all Conduit’s associated with this Client-ID.

Returns

The list of Conduit associated with this application.

Return type

list[Conduit]

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_subscription(subscription_id: str, *, token_for: str | PartialUser | None = None) EventsubSubscription | None

This function is a coroutine.

Fetches a specific Eventsub Subscription for either webhook or websocket.

Note

This endpoint returns disabled WebSocket subscriptions for a minimum of 1 minute as compared to webhooks which returns disabled subscriptions for a minimum of 10 days.

Parameters
  • subscription_id (str) – The specific subscription ID to fetch.

  • 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.

Return type

EventsubSubscription | None

async fetch_eventsub_subscriptions(*, token_for: str | PartialUser | None = None, type: str | None = None, user_id: str | PartialUser | None = None, subscription_id: str | None = None, conduit_id: str | 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, user_id, conduit_id, and subscription_id are mutually exclusive and only one can be passed, otherwise ValueError will be raised.

This endpoint returns disabled WebSocket subscriptions for a minimum of 1 minute as compared to webhooks which returns disabled subscriptions for a minimum of 10 days.

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.

  • subscription_id (str | None) – The specific subscription ID to fetch.

  • conduit_id (str | None) – Filter subscriptions by conduit ID.

  • 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’, ‘subscription_id’, or ‘type’ can be provided.

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]

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]

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.

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_user(*, id: str | int | None = None, login: str | None = None, token_for: str | twitchio.user.PartialUser | None = None) twitchio.user.User | None

This function is a coroutine.

Fetch information about one user.

Note

You may look up a specific user using their user ID or login name.

If you don’t specify an ID or login name 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
  • id (str | int | None) – The id of the user to fetch information about.

  • login (str | None) – The login name of the user 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 twitchio.User object.

Return type

twitchio.User

Raises

ValueError – Please provide only one of id or login.

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.

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.

property http: ManagedHTTPClient

Property exposing the internal ManagedHTTPClient used for requests to the Twitch API.

Warning

Altering or changing this class during runtime may have unwanted side-effects. It is exposed for developer easabilty, especially when OAuth or Device Code Flow methods are required. It is not intended to replace the use of the built-in methods of the Client or other models.

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_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.

  • 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()
safe_dispatch(name: str, *, payload: Any | None = None) None

Method to dispatch a custom event.

When an event is dispatched all listeners listening to the event, coroutine functions defined on the Client with the same name, and wait_for() waiting for the event will be triggered.

Internally the Client uses a method similar to this, however to avoid conflicts with built-in events it is not documented and you should use this method instead when needing a custom event dispatched.

This method avoids conflicts with internal events by prefixing the name of the event with event_safe_; specifically in this case safe_ is added between the event_ prefix and the name of the event.

All events in TwitchIO, including custom ones, must take between 0 or 1 arguments only. If None is passed to the payload parameter (default), the event will be dispatched with no arguments attached. Otherwise you can provide one parameter payload which (ideally) is a class containing all the information and methods needed in your event. Keep in mind that events expect consistency; E.g. If your event takes a payload argument it should always take a payload argument and vice versa. If designing an ext for TwitchIO this also will be inline with how end-users will expect events to work.

Note

If you intend on using this in a custom ext for example; consider also adding a small prefix to the name to identify your extension from others.

Warning

Overriding this method is highly discouraged. Any changes made to the safe name of the event may have hard to track and unwanted side effects. TwitchIO uses events internally and any changes to these dispatched events internally by users may also lead to consequences such as being rate limted or banned by Twitch, banned by broadcasters or; memory, CPU, network and other performance issues.

Parameters
  • name (str) – The name of the event you wish to dispatch. Remember the name of the event will be prefixed with event_safe_.

  • payload (Any | None) – The payload object dispatched to all your listeners. Defaults to None which would pass 0 arguments to all listeners.

Example

class CoolPayload:

    def __init__(self, number: int) -> None:
        self.number = number

class CoolComponent(commands.Component):

    @commands.Component.listener()
    async def event_safe_cool(self, payload: CoolPayload) -> None:
        print(f"Received 'cool' event with number: {payload.number}")


# Somewhere...
payload = CoolPayload(number=9)
client.safe_dispatch("cool", payload)
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.

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]

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 set_adapter(adapter: BaseAdapter[Any]) None

This function is a coroutine.

Method which sets and starts a new web adapter which inherits from either AiohttpAdapter or StarlettepAdapter or implements the BaseAdapter specifications.

Parameters

adapter (BaseAdapter) – The new adapter to assign and start.

Return type

None

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.

  • 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.

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.

websocket_subscriptions() Any

Important

AutoClient does not implement this method.

async subscribe_websocket(*args: Any, **kwargs: Any) Any

Important

AutoClient does not implement this method.

async subscribe_webhook(*args: Any, **kwargs: Any) Any

Important

AutoClient does not implement this method.

async start_dcf(*args: Any, **kwargs: Any) Any

Important

AutoClient does not implement this method.

async login_dcf(*args: Any, **kwargs: Any) Any

Important

AutoClient does not implement this method.