Client Reference¶
For twitchio.AutoClient and Conduit support see: Conduits
- defadd_listener
- asyncadd_token
- asyncclose
- asynccreate_conduit
- defcreate_partialuser
- asyncdelete_all_eventsub_subscriptions
- asyncdelete_eventsub_subscription
- asyncdelete_videos
- asyncdelete_websocket_subscription
- asyncevent_error
- asyncfetch_auth_by_users
- asyncfetch_badges
- asyncfetch_channel
- asyncfetch_channels
- asyncfetch_chatters_color
- asyncfetch_cheermotes
- asyncfetch_classifications
- async forfetch_clips
- asyncfetch_conduit
- asyncfetch_conduits
- async forfetch_drop_entitlements
- asyncfetch_emote_sets
- asyncfetch_emotes
- asyncfetch_eventsub_subscription
- 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_user
- asyncfetch_users
- async forfetch_videos
- @listen
- asyncload_tokens
- asynclogin
- asynclogin_dcf
- defremove_listener
- asyncremove_token
- defrun
- defsafe_dispatch
- asyncsave_tokens
- async forsearch_categories
- async forsearch_channels
- asyncset_adapter
- asyncsetup_hook
- asyncstart
- asyncstart_dcf
- asyncsubscribe_webhook
- asyncsubscribe_websocket
- asyncupdate_entitlements
- asyncupdate_extensions
- asyncwait_for
- asyncwait_until_ready
- defwebsocket_subscriptions
- class twitchio.Client(*, client_id: str, client_secret: str | None = None, bot_id: str | None = None, **options: Unpack[ClientOptions])¶
The TwitchIO Client.
The
Clientacts as an entry point to the Twitch API, EventSub and OAuth and serves as a base for chat-bots.Botinherits from this class and such should be treated as aClientwith an in-built commands extension.You don’t need to
start()orrun()theClientto 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
strto set as the redirect uri for anything relating to Twitch OAuth viatwitchio.web.StarletteAdapterortwitchio.web.AiohttpAdapter. This is a convenience attribute, it is preferred you use a customStarletteAdapterorAiohttpAdapterinstead.scopes (twitchio.Scopes | None) –
An optional
Scopesobject 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.ClientSessionto use for all HTTP requests including any requests made withAsset’s.adapter (twitchio.StarletteAdapter | twitchio.AiohttpAdapter | None) –
An optional
twitchio.web.StarletteAdapterortwitchio.web.AiohttpAdapterto 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.AiohttpAdapterwith default settings.fetch_client_user (bool) – An optional bool indicating whether to fetch and cache the client/bot accounts own
Userobject to use withuser. Defaults toTrue. You must passbot_idfor this parameter to have any effect.
- property adapter: BaseAdapter[Any]¶
Property returning the
AiohttpAdapterorStarlettepAdapterthe bot is currently running.
- property http: ManagedHTTPClient¶
Property exposing the internal
ManagedHTTPClientused 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
Clientor other models.
- 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
AiohttpAdapterorStarlettepAdapteror implements theBaseAdapterspecifications.- Parameters
adapter (
BaseAdapter) – The new adapter to assign and start.- Return type
None
- 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
Clientif 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
UserorPartialUserassociated with with the Client/Bot.In most cases this will be a
Userobject. Could bePartialUserwhen passingFalseto thefetch_client_userkeyword parameter of Client.Could be
Noneif nobot_idwas passed to the Client constructor.Important
If
bot_idhas not been passed to the constructor ofClientthis 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.
- 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
Clientwith the same name, andwait_for()waiting for the event will be triggered.Internally the
Clientuses 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 casesafe_is added between theevent_prefix and the name of the event.All events in TwitchIO, including custom ones, must take between
0or1arguments only. IfNoneis passed to the payload parameter (default), the event will be dispatched with no arguments attached. Otherwise you can provide one parameterpayloadwhich (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 anextfor 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
extfor 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
Nonewhich would pass0arguments 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 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_dcf(*, load_token: bool = True, save_token: bool = True, scopes: Scopes | None = None, force_flow: bool = False) DeviceCodeFlowResponse | None¶
This function is a coroutine.
Warning
DCF is intended to be used when your application cannot safely store a
client-secret. E.g. on a users device (phone, tv, etc…).Note
This method should be called before
start_dcf().Method to initiate a DCF (Device Code Flow) and setup the
Client.If a token has been loaded automcatically via this method, a DCF authorization flow will not be initiated. You can change this behaviour by setting the
force_flowkeyword-only argument toTrue. This will force the user to re-authenticate via DCF.This method works together with
start_dcf()to complete the flow and setup theClient. You should callstart_dcf()after this method.- Parameters
load_token (bool) – Whether to attempt to load an existing saved token. Defaults to
True.save_token (bool) – Whether to save any tokens loaded into the
Clientat close. Defaults toTrue.scopes (
Scopes|None) – AScopesobject with the required scopes set for the user to authenticate with. If you pass these to theClientconstructor you do not need to pass them here.force_flow (bool) – Wtheer to force the user to authenticate, even when an existing token is found and valid. Useful when you require new scopes or for testing. Defaults to
False.
- Returns
DeviceCodeFlowResponse – A dict with the keys:
device_code,expires_in,interval,user_codeandverification_uri.None – The Device Code Flow was not initiated; E.g. an existing token was loaded and
force_flowwasFalse.
- Raises
RuntimeError – Invalid
client_idwas passed to theClient.RuntimeError – You cannot use a
client_secretwith DCF.HTTPException – An error was raised making a request to Twitch.
- async start_dcf(*, device_code: str | None = None, interval: int = 5, timeout: int | None = 90, scopes: twitchio.authentication.scopes.Scopes | None = None, block: bool = True) None¶
This function is a coroutine.
Warning
DCF is intended to be used when your application cannot safely store a
client-secret. E.g. on a users device (phone, tv, etc…).Note
The
login_dcf()method must be called before this method.login_dcf()provides a response payload and other useful data that can be used withstart_dcf().Method to start the
Clientwith DCF (Device Code Flow).Unlike
start()this method must be called afterlogin_dcf()and does not directly call this method itself.Unlike
start()this method can be used to run theClientwith or without asynchronous blocking behaviours. However due to the design ofDCFthelogin_dcf()method must still be called first.When the
device_codeparameter isNone(default), this method will not wait for an authorization response from Twitch. However, a token must be loaded prior to this method being called (usually automatically inlogin_dcf()), else aRuntimeErrorwill be raised.- Parameters
device_code (
str|None) – The device code received as a response fromlogin_dcf(). Iflogin_dcf()loaded a saved token, you can safely disregard this parameter, unless you are forcing a user to reauthenticate.interval (
int) – Anintas seconds, passed to determine how long we should wait before checking the users authentication status in the DCF. This can be changed however the provided interval in the response fromlogin_dcf()is usually preferred. Defaults to5.timeout (
int|None) – Anintas seconds before this method will timeout waiting for a user to complete the DCF. Could beNoneto disable timeout. Defaults to90. If a timeout occurs aTimeoutErrorwill be raised.scopes (
Scopes|None) – AScopesthat will be granted by the user during the DCF. This should be the same scopes passed tologin_dcf(). If scopes are assigned or passed to theClientyou do not need to pass scopes here or inlogin_dcf(). Defaults toNonewhich means you would need to pass scopes to the client.block (
bool) – A bool indicating whether to run theClientin a asynchronously blocking loop. This is the default and same behaviour asstart(). When set toFalse, yourClientwill be logged in and can be used standalone. Defaults toTrue.
- Raises
RuntimeError –
login_dcf()must be called before this method.RuntimeError – A token and refresh pair must be loaded prior to calling this method, or you must pass the
device_codeparameter.RuntimeError – A valid
Usercould not be fetched with the token received.DeviceCodeFlowException – An exception was raised during a request to Twitch for DCF. Check the device code is valid.
HTTPException – An exception was raised during a request to Twitch.
TimeoutError – Timed-out waiting for the user to complete the DCF.
- 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
Clientshould callload_tokens()during login automatically. Defaults toTrue.save_tokens (bool) – Optional bool which inicates whether the
Clientshould 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.
load_tokens (bool) – Optional bool which indicates whether the
Clientshould callload_tokens()duringlogin()automatically. Defaults toTrue.save_tokens (bool) – Optional bool which inicates whether the
Clientshould 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.
load_tokens (bool) – Optional bool which indicates whether the
Clientshould callload_tokens()duringlogin()automatically. Defaults toTrue.save_tokens (bool) – Optional bool which inicates whether the
Clientshould 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
Clientgracefully.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 toNonewhich 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
Clientstarts.Note
This method is called by the client during
login()but beforesetup_hook()when theload_tokenskeyword-argument isTruein 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_tokenskeyword-argument isTruein 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
strwhich indicates which event to listen to. This should include theevent_prefix. Defaults toNonewhich uses the coroutine function name passed instead.
- Raises
ValueError – The
eventstring passed should start withevent_.ValueError – The
eventstring 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
Nonewhen 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
ClientorBotand can come from multiple sources, such as internally, or via EventSub. Unlike the overridable events built into botClientandBot, 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.PartialUserobjects.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
PartialUserfor.user_login (str | None) – Login name of the user you wish to create a
PartialUserfor, if available.
- Returns
A
PartialUserobject.- 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
ChatBadgeobjects- 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
EmoteSetobjects.- 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
ChatterColorobjects 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
ChannelInfoobjects.- Return type
list[
ChannelInfo]
- 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
ChannelInfo– Channel information as aChannelInfoobject.None – No channel could be found.
- 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
Cheermoteobjects.- 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
ContentClassificationLabelobjects.- Return type
- 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
HTTPAsyncIteratorFetches 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.
- 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
HTTPAsyncIteratorFetches 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
UserExtensionobjects.- 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
ActiveExtensionsobject.- 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
GlobalEmoteobjects.- Return type
list[
twitchio.GlobalEmote]
- 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
HTTPAsyncIteratorFetches 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.Teamobject.- Return type
- 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
HTTPAsyncIteratorFetches 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.Gameobjects.- 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
Gameobject 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.Gameobject 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.Userobjects.- Return type
list[
twitchio.User]- Raises
ValueError – The combined number of ‘ids’ and ‘logins’ must not exceed 100 elements.
- 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.Userobject.- Return type
- Raises
ValueError – Please provide only one of id or login.
- 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
HTTPAsyncIteratorSearches 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
HTTPAsyncIteratorSearches 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]
- 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
HTTPAsyncIteratorFetch a list of
Videoobjects 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
- fetch_stream_markers(*, video_id: str, token_for: str | PartialUser, first: int = 20, max_results: int | None = None) HTTPAsyncIterator[VideoMarkers]¶
This function returns a
HTTPAsyncIteratorFetches 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_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
HTTPAsyncIteratorFetches 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.EntitlementStatusobjects.- Return type
- Raises
ValueError – You may only specifiy a maximum of 100 ids.
- 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
- Raises
ValueError – You may only fetch a maximum of
10user IDs at a time.
- async subscribe_websocket(payload: SubscriptionPayload, *, as_bot: bool | None = None, 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.
- Parameters
payload (
twitchio.eventsub.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 onClientbut will default to True onBottoken_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_idaccount. 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, *, callback_url: str | None = None, eventsub_secret: str | None = None) SubscriptionResponse | None¶
This function is a coroutine.
Subscribe to an EventSub Event via Webhook.
Important
Usually you wouldn’t use webhooks to subscribe to the
ChatMessageSubscriptionsubscription.Consider using
subscribe_websocket()for this subscription.- Parameters
payload (
SubscriptionPayload) – The payload which should include the required conditions to subscribe to.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, 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.followFor 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 toNone.
- Return type
EventsubSubscriptions
- Raises
ValueError – Only one of ‘status’, ‘user_id’, ‘subscription_id’, or ‘type’ can be provided.
- 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 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.
- websocket_subscriptions() dict[str, twitchio.payloads.WebsocketSubscriptionData]¶
Method which returns a mapping of currently active EventSub subscriptions with a websocket transport on this client.
The returned mapping contains the subscription ID as a key to a
WebsocketSubscriptionDatavalue containing the relevant subscription data.- Returns
A mapping of currently active websocket subscriptions on the client.
- Return type
dict[
str,WebsocketSubscriptionData]
- async delete_websocket_subscription(id: str, *, force: bool = False) WebsocketSubscriptionData¶
This function is a coroutine.
Delete an EventSub subsctiption with a Websocket Transport.
This method is a helper method to remove a websocket subscription currently active on this client. This method also cleans up any websocket connections that have no remaining subscriptions after the subscription is removed.
Note
Make sure the subscription is currently active on this Client instance. You can check currently active websocket subscriptions via
websocket_subscriptions().- Parameters
id (str) – The Eventsub subscription ID. You can view currently active subscriptions via
websocket_subscriptions().force (bool) –
When set to
True, the subscription will be forcefully removed from the Client, regardless of any HTTPException’s raised during the call to Twitch.When set to
False, if an exception is raised, the subscription will remain on the Client websocket. Defaults toFalse.
- Returns
The data associated with the removed subscription.
- Return type
- Raises
ValueError – The subscription with the provided ID could not be found on this client.
HTTPException – Removing the subscription from Twitch failed.
- 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 fetch_conduit(conduit_id: str) twitchio.models.eventsub_.Conduit | None¶
This function is a coroutine.
Method which retrieves a
Conduitfrom the API, with the provided ID.
- async fetch_conduits() list[twitchio.models.eventsub_.Conduit]¶
This function is a coroutine.
Method to retrieve all
Conduit’s associated with this Client-ID.
- async create_conduit(shard_count: int) Conduit¶
This function is a coroutine.
Method to create a
Conduiton the API.- Parameters
shard_count (int) – The amount of shards to assign to the Conduit. Must be between
1and20_000.- Raises
ValueError –
shard_countmust be between1and20_000.- Returns
The newly created
Conduit.- Return type
TwitchIO - Documentation