Client
ClientApp
¶
Bases: BaseClient
Twitch EventSub WebSocket client for app-based connections.
Handles conduit-based event subscriptions, shard management, and WebSocket connections for Twitch applications.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_id
|
str
|
The application's unique client identifier. |
required |
client_secret
|
str
|
The application's client secret for secure authentication. |
required |
**options
|
Any
|
Additional configuration options
|
{}
|
application
property
¶
eventsub
property
¶
Get the app events handler for creating EventSub subscriptions.
Note
Subscription creation behavior is controlled by the ignore_conflict option set during client initialization.
Event Dispatching
Events are dispatched to specific handlers, or with _raw suffix if
no model exists. You can force newer unsupported versions for testing -
these will dispatch as raw events.
Returns:
| Type | Description |
|---|---|
AppEvents
|
The events handler for app-based subscriptions. |
tokens
property
¶
tokens_validity
property
¶
Get token validity timestamps for all users.
Returns:
| Type | Description |
|---|---|
MappingProxyType[str, Tuple[float, float]]
|
Read-only mapping of user IDs to (last_validated, expires_in) tuples. Timestamps are in Unix epoch format. |
users_scopes
property
¶
Get the scopes for all authorized users.
Returns:
| Type | Description |
|---|---|
MappingProxyType[str, Tuple[str, ...]]
|
Read-only mapping of user IDs to their granted OAuth scopes. |
connect(conduit_id, *, shard_ids, reconnect=True)
async
¶
Connect to Twitch EventSub WebSocket with shard management.
Important: Keep All Shards Connected
You need an active WebSocket connection for every shard in your conduit.
If you have dead shards (no connection), you'll miss events. Always keep your shard count equal to your active connections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conduit_id
|
str
|
The conduit ID for event subscriptions. |
required |
shard_ids
|
Tuple[int, ...]
|
Tuple of shard IDs to check for availability. The first non-enabled shard will be used for the connection. |
required |
reconnect
|
bool
|
Whether to automatically reconnect on connection failures. |
True
|
Raises:
| Type | Description |
|---|---|
ShardError
|
If shard identification fails. |
ShardNotFound
|
If all provided shards are already enabled. |
TokenError
|
If missing a valid app access token with required scopes. |
Unauthorized
|
If the token is invalid, expired, or doesn't have the required scopes. |
NotFound
|
If conduit not found. |
ConnectionClosed
|
If WebSocket connection is closed unexpectedly. |
dispatch(event, /, *args, **kwargs)
¶
event(coro)
¶
get_token(user_id)
¶
Get stored tokens for a specific user.
Retrieves the access token and refresh token (if available) for the specified user from local storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str
|
The user identifier to retrieve tokens for. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Tuple[str, Optional[str]]]
|
The stored (access_token, refresh_token) tuple, or None if not found. |
get_token_quota(user_id)
¶
get_user_by_id(user_id)
¶
Get a UserAPI instance for an already authorized user.
Warning
This method does not validate stored tokens. If tokens are invalid or expired, API calls through the returned UserAPI may fail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str
|
The user identifier to get API access for. |
required |
Returns:
| Type | Description |
|---|---|
UserAPI
|
A UserAPI instance for the specified user. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the user_id matches the client_id (use application property instead). |
TokenError
|
If no tokens are stored for the specified user_id. |
identify_shard(conduit_id, shard_id, /, *, session_id)
async
¶
Identify a shard with the conduit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conduit_id
|
str
|
The conduit ID to register the shard with. |
required |
shard_id
|
int
|
The shard ID to identify. |
required |
session_id
|
str
|
The WebSocket session ID. |
required |
Raises:
| Type | Description |
|---|---|
ShardError
|
If shard identification fails. |
TokenError
|
If missing a valid app access token with required scopes. |
Unauthorized
|
If the token is invalid, expired, or doesn't have the required scopes. |
NotFound
|
If conduit not found. |
is_closed()
¶
Check if the client is closed.
Returns:
| Type | Description |
|---|---|
bool
|
True if the client is closed, False otherwise. |
is_ready()
¶
Check if the client is ready.
Returns:
| Type | Description |
|---|---|
bool
|
True if the client is ready, False otherwise. |
on_error(event_method, error, /, *args, **kwargs)
async
staticmethod
¶
Handle errors from event handlers.
Info
Override this method to implement custom error handling or logging behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_method
|
str
|
Event method name that caused the error. |
required |
error
|
Exception
|
The exception that occurred. |
required |
*args
|
Any
|
Event positional arguments. |
()
|
**kwargs
|
Any
|
Event keyword arguments. |
{}
|
run(conduit_id, shard_ids=(0,), *, reconnect=True, log_handler=None, log_level=None, root_logger=False)
¶
Run the client with event loop management.
Important: Keep All Shards Connected
You need an active WebSocket connection for every shard in your conduit.
If you have dead shards (no connection), you'll miss events. Always keep your shard count equal to your active connections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conduit_id
|
str
|
The conduit ID for event subscriptions. |
required |
shard_ids
|
Tuple[int, ...]
|
Tuple of shard IDs to create connections for. |
(0,)
|
reconnect
|
bool
|
Whether to automatically reconnect on connection failures. |
True
|
log_handler
|
Optional[Handler]
|
Custom logging handler. If None, uses default setup. |
None
|
log_level
|
Optional[int]
|
Logging level. If None, uses default level. |
None
|
root_logger
|
bool
|
Whether to configure the root logger. |
False
|
setup_hook()
async
¶
Hook called after client setup.
???+ info
Override this method to perform custom initialization
or setup tasks after the client is authorized.
Danger
Long-running or blocking operations in this method can block the client startup.
start(conduit_id, *, shard_ids=(0,), reconnect=True)
async
¶
Start the client by authorizing and connecting.
Important: Keep All Shards Connected
You need an active WebSocket connection for every shard in your conduit.
If you have dead shards (no connection), you'll miss events. Always keep your shard count equal to your active connections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conduit_id
|
str
|
The conduit ID for event subscriptions. |
required |
shard_ids
|
Tuple[int, ...]
|
Tuple of shard IDs to create connections for. |
(0,)
|
reconnect
|
bool
|
Whether to automatically reconnect on connection failures. |
True
|
token_maintenance_task()
¶
Start the token maintenance background task.
Info
Override this method to disable automatic token validation or implement custom token refresh behavior.
wait_until_ready()
async
¶
Wait until the client is ready.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the client is not initialized. |
ClientUser
¶
Bases: BaseClient
Twitch EventSub WebSocket client for user-based connections.
Handles user authentication, event subscriptions, and WebSocket connections for individual Twitch users with automatic token management.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_id
|
str
|
The application's unique client identifier. |
required |
client_secret
|
str
|
The application's client secret for secure authentication. |
required |
**options
|
Any
|
Additional configuration options
|
{}
|
application
property
¶
eventsub
property
¶
Get the user events handler for creating EventSub subscriptions.
Tip
You can create subscriptions even if the WebSocket is not connected. The client will automatically establish a WebSocket connection when needed.
Note
Subscription creation behavior is controlled by the ignore_conflict option set during client initialization.
Event Dispatching
Events are dispatched to specific handlers, or with _raw suffix if
no model exists. You can force newer unsupported versions for testing.
Returns:
| Type | Description |
|---|---|
UserEvents
|
The events handler for user-based subscriptions. |
tokens
property
¶
tokens_validity
property
¶
Get token validity timestamps for all users.
Returns:
| Type | Description |
|---|---|
MappingProxyType[str, Tuple[float, float]]
|
Read-only mapping of user IDs to (last_validated, expires_in) tuples. Timestamps are in Unix epoch format. |
user
property
¶
Get the authenticated user API instance.
Returns:
| Type | Description |
|---|---|
UserAPI
|
The authenticated user's API interface. |
Raises:
| Type | Description |
|---|---|
AttributeError
|
If user is not authenticated. Call login() first. |
users_scopes
property
¶
Get the scopes for all authorized users.
Returns:
| Type | Description |
|---|---|
MappingProxyType[str, Tuple[str, ...]]
|
Read-only mapping of user IDs to their granted OAuth scopes. |
connect(*, reconnect=True, mock_url=None)
async
¶
Connect to Twitch EventSub WebSocket with automatic reconnection.
Note
This method handles automatic resubscription to events after reconnection. The client will attempt to maintain all active subscriptions across connection interruptions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reconnect
|
bool
|
Whether to automatically reconnect on connection failures. |
True
|
mock_url
|
Optional[str]
|
Mock WebSocket URL for testing purposes. If provided, the client will connect to this URL instead of the official Twitch EventSub endpoint. |
None
|
Raises:
| Type | Description |
|---|---|
ConnectionClosed
|
If WebSocket connection is closed unexpectedly and reconnect is False. |
dispatch(event, /, *args, **kwargs)
¶
get_token(user_id)
¶
Get stored tokens for a specific user.
Retrieves the access token and refresh token (if available) for the specified user from local storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str
|
The user identifier to retrieve tokens for. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Tuple[str, Optional[str]]]
|
The stored (access_token, refresh_token) tuple, or None if not found. |
get_token_quota(user_id)
¶
get_user_by_id(user_id)
¶
Get a UserAPI instance for an already authorized user.
Warning
This method does not validate stored tokens. If tokens are invalid or expired, API calls through the returned UserAPI may fail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str
|
The user identifier to get API access for. |
required |
Returns:
| Type | Description |
|---|---|
UserAPI
|
A UserAPI instance for the specified user. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the user_id matches the client_id (use application property instead). |
TokenError
|
If no tokens are stored for the specified user_id. |
is_closed()
¶
Check if the client is closed.
Returns:
| Type | Description |
|---|---|
bool
|
True if the client is closed, False otherwise. |
is_ready()
¶
Check if the client is ready.
Returns:
| Type | Description |
|---|---|
bool
|
True if the client is ready, False otherwise. |
login(access_token, refresh_token, register_events=True)
async
¶
Authenticate a user with access and refresh tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
access_token
|
str
|
Valid Twitch user access token. |
required |
refresh_token
|
Optional[str]
|
Optional refresh token for automatic token renewal. |
required |
register_events
|
bool
|
Use this to automatically register events you added using the |
True
|
Raises:
| Type | Description |
|---|---|
AuthFailure
|
If the tokens are invalid or authorization fails. |
on_error(event_method, error, /, *args, **kwargs)
async
staticmethod
¶
Handle errors from event handlers.
Info
Override this method to implement custom error handling or logging behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_method
|
str
|
Event method name that caused the error. |
required |
error
|
Exception
|
The exception that occurred. |
required |
*args
|
Any
|
Event positional arguments. |
()
|
**kwargs
|
Any
|
Event keyword arguments. |
{}
|
run(access_token, refresh_token=None, *, register_events=True, reconnect=True, mock_url=None, log_handler=None, log_level=None, root_logger=False)
¶
Run the client with event loop management.
Danger
This is a blocking call that runs the client until stopped. Sets up logging and handles the async context automatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
access_token
|
str
|
Valid Twitch user access token. |
required |
refresh_token
|
Optional[str]
|
Optional refresh token for automatic token renewal. |
None
|
register_events
|
bool
|
Use this to automatically register events you added using the |
True
|
reconnect
|
bool
|
Whether to automatically reconnect on connection failures. |
True
|
mock_url
|
Optional[str]
|
Mock WebSocket URL for testing purposes. |
None
|
log_handler
|
Optional[Handler]
|
Custom logging handler. If None, uses default setup. |
None
|
log_level
|
Optional[int]
|
Logging level. If None, uses default level. |
None
|
root_logger
|
bool
|
Whether to configure the root logger. Default False. |
False
|
setup_hook()
async
¶
Hook called after client setup.
???+ info
Override this method to perform custom initialization
or setup tasks after the client is authorized.
Danger
Long-running or blocking operations in this method can block the client startup.
start(access_token, refresh_token=None, *, register_events=True, reconnect=True, mock_url=None)
async
¶
Start the client by authorizing, logging in, and connecting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
access_token
|
str
|
Valid Twitch user access token. |
required |
refresh_token
|
Optional[str]
|
Optional refresh token for automatic token renewal. |
None
|
register_events
|
bool
|
Use this to automatically register events you added using the |
True
|
reconnect
|
bool
|
Whether to automatically reconnect on connection failures. |
True
|
mock_url
|
Optional[str]
|
Mock WebSocket URL for testing purposes. |
None
|
Raises:
| Type | Description |
|---|---|
TokenError
|
If the access token is invalid or missing required scopes. |
Unauthorized
|
If the token is expired or doesn't have the required permissions. |
ConnectionClosed
|
If WebSocket connection is closed unexpectedly and reconnect is False. |
HTTPException
|
If there's an HTTP error during startup. |
token_maintenance_task()
¶
Start the token maintenance background task.
Info
Override this method to disable automatic token validation or implement custom token refresh behavior.
wait_until_ready()
async
¶
Wait until the client is ready.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the client is not initialized. |
MultiShardClientApp
¶
Bases: ClientApp
Multi-shard Twitch EventSub WebSocket client for high-throughput applications.
Note
This client is designed for applications expecting high event volumes. For most use cases, the standard ClientApp is sufficient and simpler to use.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_id
|
str
|
The application's unique client identifier. |
required |
shard_connect_timeout
|
Timeout in seconds for individual shard connections. |
required | |
client_secret
|
str
|
The application's client secret for secure authentication. |
required |
**kwargs
|
Any
|
Additional configuration options passed to the parent ClientApp. |
{}
|
application
property
¶
eventsub
property
¶
Get the app events handler for creating EventSub subscriptions.
Note
Subscription creation behavior is controlled by the ignore_conflict option set during client initialization.
Event Dispatching
Events are dispatched to specific handlers, or with _raw suffix if
no model exists. You can force newer unsupported versions for testing -
these will dispatch as raw events.
Returns:
| Type | Description |
|---|---|
AppEvents
|
The events handler for app-based subscriptions. |
shards
property
¶
tokens
property
¶
tokens_validity
property
¶
Get token validity timestamps for all users.
Returns:
| Type | Description |
|---|---|
MappingProxyType[str, Tuple[float, float]]
|
Read-only mapping of user IDs to (last_validated, expires_in) tuples. Timestamps are in Unix epoch format. |
users_scopes
property
¶
Get the scopes for all authorized users.
Returns:
| Type | Description |
|---|---|
MappingProxyType[str, Tuple[str, ...]]
|
Read-only mapping of user IDs to their granted OAuth scopes. |
connect(conduit_id, *, shard_ids, reconnect=True)
async
¶
Connect to Twitch EventSub with multiple shards.
Important: Keep All Shards Connected
You need an active WebSocket connection for every shard in your conduit.
If you have dead shards (no connection), you'll miss events. Always keep your shard count equal to your active connections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conduit_id
|
str
|
The conduit ID for event subscriptions. |
required |
shard_ids
|
Tuple[int, ...]
|
Tuple of shard IDs to create connections for. |
required |
reconnect
|
bool
|
Whether shards should automatically reconnect on failures. |
True
|
Raises:
| Type | Description |
|---|---|
ShardError
|
If any shard fails to connect with an unrecoverable error. |
NotFound
|
If the conduit is not found. |
Unauthorized
|
If authentication fails. |
BadRequest
|
If request parameters are invalid. |
ConnectionClosed
|
If connections are closed unexpectedly without reconnect enabled. |
dispatch(event, /, *args, **kwargs)
¶
event(coro)
¶
get_shard(shard_id)
¶
get_token(user_id)
¶
Get stored tokens for a specific user.
Retrieves the access token and refresh token (if available) for the specified user from local storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str
|
The user identifier to retrieve tokens for. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Tuple[str, Optional[str]]]
|
The stored (access_token, refresh_token) tuple, or None if not found. |
get_token_quota(user_id)
¶
get_user_by_id(user_id)
¶
Get a UserAPI instance for an already authorized user.
Warning
This method does not validate stored tokens. If tokens are invalid or expired, API calls through the returned UserAPI may fail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str
|
The user identifier to get API access for. |
required |
Returns:
| Type | Description |
|---|---|
UserAPI
|
A UserAPI instance for the specified user. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the user_id matches the client_id (use application property instead). |
TokenError
|
If no tokens are stored for the specified user_id. |
identify_shard(conduit_id, shard_id, /, *, session_id)
async
¶
Identify a shard with the conduit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conduit_id
|
str
|
The conduit ID to register the shard with. |
required |
shard_id
|
int
|
The shard ID to identify. |
required |
session_id
|
str
|
The WebSocket session ID. |
required |
Raises:
| Type | Description |
|---|---|
ShardError
|
If shard identification fails. |
TokenError
|
If missing a valid app access token with required scopes. |
Unauthorized
|
If the token is invalid, expired, or doesn't have the required scopes. |
NotFound
|
If conduit not found. |
is_closed()
¶
Check if the client is closed.
Returns:
| Type | Description |
|---|---|
bool
|
True if the client is closed, False otherwise. |
is_ready()
¶
Check if the client is ready.
Returns:
| Type | Description |
|---|---|
bool
|
True if the client is ready, False otherwise. |
launch_shard(conduit_id, shard_id, *, reconnect)
async
¶
Launch a single shard connection.
Note
Connection failures other than the above exceptions will trigger automatic retry with exponential backoff.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conduit_id
|
str
|
The conduit ID to register the shard with. |
required |
shard_id
|
int
|
The unique identifier for this shard. |
required |
reconnect
|
bool
|
Whether this shard should attempt automatic reconnection. |
required |
Raises:
| Type | Description |
|---|---|
ShardError
|
If shard identification fails with an unrecoverable error. |
BadRequest
|
If the request parameters are invalid. |
NotFound
|
If the conduit is not found. |
Unauthorized
|
If authentication fails. |
launch_shards(conduit_id, shard_ids, *, reconnect)
async
¶
Launch multiple shard connections sequentially.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conduit_id
|
str
|
The conduit ID to register all shards with. |
required |
shard_ids
|
Tuple[int, ...]
|
Tuple of shard IDs to launch. |
required |
reconnect
|
bool
|
Whether shards should attempt automatic reconnection. |
required |
on_error(event_method, error, /, *args, **kwargs)
async
staticmethod
¶
Handle errors from event handlers.
Info
Override this method to implement custom error handling or logging behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_method
|
str
|
Event method name that caused the error. |
required |
error
|
Exception
|
The exception that occurred. |
required |
*args
|
Any
|
Event positional arguments. |
()
|
**kwargs
|
Any
|
Event keyword arguments. |
{}
|
run(conduit_id, shard_ids=(0,), *, reconnect=True, log_handler=None, log_level=None, root_logger=False)
¶
Run the client with event loop management.
Important: Keep All Shards Connected
You need an active WebSocket connection for every shard in your conduit.
If you have dead shards (no connection), you'll miss events. Always keep your shard count equal to your active connections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conduit_id
|
str
|
The conduit ID for event subscriptions. |
required |
shard_ids
|
Tuple[int, ...]
|
Tuple of shard IDs to create connections for. |
(0,)
|
reconnect
|
bool
|
Whether to automatically reconnect on connection failures. |
True
|
log_handler
|
Optional[Handler]
|
Custom logging handler. If None, uses default setup. |
None
|
log_level
|
Optional[int]
|
Logging level. If None, uses default level. |
None
|
root_logger
|
bool
|
Whether to configure the root logger. |
False
|
setup_hook()
async
¶
Hook called after client setup.
???+ info
Override this method to perform custom initialization
or setup tasks after the client is authorized.
Danger
Long-running or blocking operations in this method can block the client startup.
start(conduit_id, *, shard_ids=(0,), reconnect=True)
async
¶
Start the client by authorizing and connecting.
Important: Keep All Shards Connected
You need an active WebSocket connection for every shard in your conduit.
If you have dead shards (no connection), you'll miss events. Always keep your shard count equal to your active connections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conduit_id
|
str
|
The conduit ID for event subscriptions. |
required |
shard_ids
|
Tuple[int, ...]
|
Tuple of shard IDs to create connections for. |
(0,)
|
reconnect
|
bool
|
Whether to automatically reconnect on connection failures. |
True
|
token_maintenance_task()
¶
Start the token maintenance background task.
Info
Override this method to disable automatic token validation or implement custom token refresh behavior.
wait_until_ready()
async
¶
Wait until the client is ready.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the client is not initialized. |