Client Reference¶
- defadd_listener
- asyncadd_token
- asyncclose
- defcreate_partialuser
- asyncdelete_all_eventsub_subscriptions
- asyncdelete_eventsub_subscription
- asyncdelete_videos
- asyncevent_error
- asyncfetch_badges
- asyncfetch_channels
- asyncfetch_chatters_color
- asyncfetch_cheermotes
- asyncfetch_classifications
- async forfetch_clips
- async forfetch_drop_entitlements
- asyncfetch_emote_sets
- asyncfetch_emotes
- asyncfetch_eventsub_subscriptions
- async forfetch_extension_transactions
- asyncfetch_extensions
- asyncfetch_game
- asyncfetch_games
- async forfetch_stream_markers
- async forfetch_streams
- asyncfetch_team
- async forfetch_top_games
- asyncfetch_users
- async forfetch_videos
- @listen
- asyncload_tokens
- asynclogin
- defremove_listener
- asyncremove_token
- defrun
- asyncsave_tokens
- async forsearch_categories
- async forsearch_channels
- asyncsetup_hook
- asyncstart
- asyncsubscribe_webhook
- asyncsubscribe_websocket
- asyncupdate_entitlements
- asyncupdate_extensions
- asyncwait_for
- asyncwait_until_ready
- class twitchio.Client(*, client_id: str, client_secret: str, bot_id: str | None = None, **options: Unpack[ClientOptions])¶
The TwitchIO Client.
The
Client
acts as an entry point to the Twitch API, EventSub and OAuth and serves as a base for chat-bots.Bot
inherits from this class and such should be treated as aClient
with an in-built commands extension.You don’t need to
start()
orrun()
theClient
to use it soley as a HTTP Wrapper, but you must stilllogin()
with this use case.- 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 | None) –
An optional str which should be the User ID associated with the Bot Account.
It is highly recommended setting this parameter as it will allow TwitchIO to use the bot’s own tokens where appropriate and needed.
redirect_uri (str | None) – An optional
str
to set as the redirect uri for anything relating to Twitch OAuth viatwitchio.web.StarletteAdapter
ortwitchio.web.AiohttpAdapter
. This is a convenience attribute, it is preferred you use a customStarletteAdapter
orAiohttpAdapter
instead.scopes (twitchio.Scopes | None) –
An optional
Scopes
object to use as defaults when using anything related to Twitch OAuth.Useful when you want to set default scopes for users to authenticate with.
session (aiohttp.ClientSession | None) – An optional
aiohttp.ClientSession
to use for all HTTP requests including any requests made withAsset
’s.adapter (twitchio.StarletteAdapter | twitchio.AiohttpAdapter | None) –
An optional
twitchio.web.StarletteAdapter
ortwitchio.web.AiohttpAdapter
to use as the clients web server adapter.The adapter is a built-in webserver used for OAuth and when needed for EventSub over Webhooks.
When this is not provided, it will default to a
twitchio.web.AiohttpAdapter
with default settings.fetch_client_user (bool) – An optional bool indicating whether to fetch and cache the client/bot accounts own
User
object to use withuser
. Defaults toTrue
. You must passbot_id
for this parameter to have any effect.
- 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:
Warning
This method returns sensitive information such as user-tokens. You should take care not to expose these tokens.
- 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.
- property user: twitchio.user.User | twitchio.user.PartialUser | None¶
Property which returns the
User
orPartialUser
associated with with the Client/Bot.In most cases this will be a
User
object. Could bePartialUser
when passingFalse
to thefetch_client_user
keyword parameter of Client.Could be
None
if nobot_id
was passed to the Client constructor.Important
If
bot_id
has not been passed to the constructor ofClient
this will returnNone
.
- 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 setup_hook() None ¶
Method called after
login()
has been called but before the client is ready.start()
callslogin()
internally for you, so when usingstart()
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 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 usingstart()
.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 callload_tokens()
during login automatically. Defaults toTrue
.save_tokens (bool) – Optional bool which inicates whether the
Client
should callsave_tokens()
during theclose()
automatically. Defaults toTrue
.
- 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 callload_tokens()
duringlogin()
automatically. Defaults toTrue
.save_tokens (bool) – Optional bool which inicates whether the
Client
should callsave_tokens()
during theclose()
automatically. Defaults toTrue
.
Examples
import asyncio import twitchio async def main() -> None: client = twitchio.Client(...) async with client: await client.start()
- 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 callload_tokens()
duringlogin()
automatically. Defaults toTrue
.save_tokens (bool) – Optional bool which inicates whether the
Client
should callsave_tokens()
during theclose()
automatically. Defaults toTrue
.
Examples
client = twitchio.Client(...) client.run()
- 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()
orlogin()
to call thesave_tokens()
coroutine. Defaults toNone
which won’t override.
Examples
async def close(self) -> None: # Own clenup logic... ... await super().close()
- 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 insetup_hook()
or in any callsetup_hook()
is waiting for execution to complete, will completely deadlock the Client.
- 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 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
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)
- 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.
- 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 beforesetup_hook()
when theload_tokens
keyword-argument isTrue
in either,run()
,start()
orlogin()
(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 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 isTrue
in either,run()
,start()
orlogin()
(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.
- 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 theevent_
prefix. Defaults toNone
which uses the coroutine function name passed instead.
- Raises
ValueError – The
event
string passed should start withevent_
.ValueError – The
event
string passed must not ==event_
.TypeError – The listener callback must be a coroutine function.
- 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 viaadd_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.
- @ 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
orBot
and can come from multiple sources, such as internally, or via EventSub. Unlike the overridable events built into botClient
andBot
, 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"
.
- 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
- 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
- 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_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_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_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
-
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_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 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
- 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
]
-
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
- 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_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
]
- 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_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 .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
]
-
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.
- 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
-
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_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 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
- Raises
ValueError – You may only specifiy a maximum of 100 ids.
- async subscribe_websocket(payload: SubscriptionPayload, *, as_bot: bool = False, 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 onClient
but will default to True onBot
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 subscribe_webhook(payload: SubscriptionPayload, *, as_bot: bool = False, 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 onClient
but will default to True onBot
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 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 toNone
.
- Return type
EventsubSubscriptions
- Raises
ValueError – Only one of ‘status’, ‘user_id’, or ‘type’ can be provided.
- 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_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.