Twitch API#
This is the base of this library, it handles authentication renewal, error handling and permission management.
Look at the Twitch API reference for a more detailed documentation on what each endpoint does.
Example Usage#
from twitchAPI.twitch import Twitch
from twitchAPI.helper import first
import asyncio
async def twitch_example():
# initialize the twitch instance, this will by default also create a app authentication for you
twitch = await Twitch('app_id', 'app_secret')
# call the API for the data of your twitch user
# this returns a async generator that can be used to iterate over all results
# but we are just interested in the first result
# using the first helper makes this easy.
user = await first(twitch.get_users(logins='your_twitch_user'))
# print the ID of your user or do whatever else you want with it
print(user.id)
await twitch.close()
# run this example
asyncio.run(twitch_example())
Working with the API results#
The API returns a few different types of results.
TwitchObject#
A lot of API calls return a child of TwitchObject
in some way (either directly or via generator).
You can always use the to_dict()
method to turn that object to a dictionary.
Example:
blocked_term = await twitch.add_blocked_term('broadcaster_id', 'moderator_id', 'bad_word')
print(blocked_term.id)
IterTwitchObject#
Some API calls return a special type of TwitchObject. These usually have some list inside that you may want to dicrectly itterate over in your API usage but that also contain other usefull data outside of that List.
Example:
lb = await twitch.get_bits_leaderboard()
print(lb.total)
for e in lb:
print(f'#{e.rank:02d} - {e.user_name}: {e.score}')
AsyncIterTwitchObject#
A few API calls will have usefull data outside of the list the pagination itterates over. For those cases, this object exist.
Example:
schedule = await twitch.get_channel_stream_schedule('user_id')
print(schedule.broadcaster_name)
async for segment in schedule:
print(segment.title)
AsyncGenerator#
AsyncGenerators are used to automatically itterate over all possible resuts of your API call, this will also automatically handle pagination for you.
In some cases (for example stream schedules with repeating entries), this may result in a endless stream of entries returned so make sure to add your
own exit conditions in such cases.
The generated objects will always be children of TwitchObject
, see the docs of the API call to see the exact
object type.
Example:
async for tag in twitch.get_all_stream_tags():
print(tag.tag_id)
Authentication#
The Twitch API knows 2 different authentications. App and User Authentication. Which one you need (or if one at all) depends on what calls you want to use.
Its always good to get at least App authentication even for calls where you don’t need it since the rate limits are way better for authenticated calls.
App Authentication#
By default, The lib will try to attempt to create a App Authentication on Initialization:
from twitchAPI.twitch import Twitch
twitch = await Twitch('my_app_id', 'my_app_secret')
You can set a Auth Scope like this:
from twitchAPI.twitch import Twitch, AuthScope
twitch = await Twitch('my_app_id', 'my_app_secret', target_app_auth_scope=[AuthScope.USER_EDIT])
If you want to change the AuthScope later use this:
await twitch.authenticate_app(my_new_scope)
If you don’t want to use App Authentication, Initialize like this:
from twitchAPI.twitch import Twitch
twitch = await Twitch('my_app_id', authenticate_app=False)
User Authentication#
Only use a user auth token, use this:
from twitchAPI.twitch import Twitch
twitch = await Twitch('my_app_id', authenticate_app=False)
# make sure to set the second parameter as the scope used to generate the token
await twitch.set_user_authentication('token', [], 'refresh_token')
Use both App and user Authentication:
from twitchAPI.twitch import Twitch
twitch = await Twitch('my_app_id', 'my_app_secret')
# make sure to set the second parameter as the scope used to generate the token
await twitch.set_user_authentication('token', [], 'refresh_token')
To get a user auth token, the user has to explicitly click “Authorize” on the twitch website. You can use various online services to generate a token or use my build in authenticator.
See twitchAPI.oauth
for more info on my build in authenticator.
Authentication refresh callback#
Optionally you can set a callback for both user access token refresh and app access token refresh.
from twitchAPI.twitch import Twitch
async def user_refresh(token: str, refresh_token: str):
print(f'my new user token is: {token}')
async def app_refresh(token: str):
print(f'my new app token is: {token}')
twitch = await Twitch('my_app_id', 'my_app_secret')
twitch.app_auth_refresh_callback = app_refresh
twitch.user_auth_refresh_callback = user_refresh
Class Documentation#
- class twitchAPI.twitch.Twitch#
Bases:
object
Twitch API client
- __init__(app_id, app_secret=None, authenticate_app=True, target_app_auth_scope=None, base_url='https://api.twitch.tv/helix/', auth_base_url='https://id.twitch.tv/oauth2/', session_timeout=_SENTINEL.sentinel)#
- Parameters:
app_id¶ (
Default:) – Your app idapp_secret¶ (
Default:) – Your app secret, leave as None if you only want to use User AuthenticationDefault:None
authenticate_app¶ (
Default:) – If true, auto generate a app token on startupDefault:True
target_app_auth_scope¶ (
Default:) – AuthScope to use ifauthenticate_app
is TrueDefault:None
base_url¶ (
Default:) – The URL to the Twitch APIDefault:TWITCH_API_BASE_URL
auth_base_url¶ (
Default:) – The URL to the Twitch API auth serverDefault:TWITCH_AUTH_BASE_URL
session_timeout¶ (
Default:) – Override the time in seconds before any request times out. Defaults to aiohttp default (300 seconds)-
logger: Default:#
The logger used for Twitch API call related log messages
-
user_auth_refresh_callback: Default:#
If set, gets called whenever a user auth token gets refreshed. Parameter: Auth Token, Refresh Token
Default:None
-
app_auth_refresh_callback: Default:#
If set, gets called whenever a app auth token gets refreshed. Parameter: Auth Token
Default:None
-
session_timeout: Default:#
Override the time in seconds before any request times out. Defaults to aiohttp default (300 seconds)
-
auto_refresh_auth: Default:#
If set to true, auto refresh the auth token once it expires.
Default:True
-
base_url: Default:#
The URL to the Twitch API used
- async static close()#
Gracefully close the connection to the Twitch API
- get_user_auth_scope()#
- Return type:
- Default:
Returns the set User auth Scope
- has_required_auth(required_type, required_scope)#
- Return type:
- Default:
- async refresh_used_token()#
Refreshes the currently used token
- async authenticate_app(scope)#
Authenticate with a fresh generated app token
- Parameters:
scope¶ (
Default:) – List of Authorization scopes to use- Raises:
TwitchAuthorizationException – if the authentication fails
- Return type:
Default:- Returns:
None
- async set_app_authentication(token, scope)#
Set a app token, most likely only used for testing purposes
- Parameters:
token¶ (
Default:) – the app tokenscope¶ (
Default:) – List of Authorization scopes that the given app token has- async set_user_authentication(token, scope, refresh_token=None, validate=True)#
Set a user token to be used.
- Parameters:
token¶ (
Default:) – the generated user tokenscope¶ (
Default:) – List of Authorization Scopes that the given user token hasrefresh_token¶ (
Default:) – The generated refresh token, has to be provided ifauto_refresh_auth
is TrueDefault:None
validate¶ (
Default:) – if true, validate the set token for being a user auth token and having the required scopeDefault:True
- Raises:
ValueError – if
auto_refresh_auth
is True but refresh_token is not setMissingScopeException – if given token is missing one of the required scopes
InvalidTokenException – if the given token is invalid or for a different client id
- get_app_token()#
Returns the app token that the api uses or None when not authenticated.
- Return type:
- Default:
- Returns:
app token
- get_user_auth_token()#
Returns the current user auth token, None if no user Authentication is set
- Return type:
- Default:
- Returns:
current user auth token
- async get_refreshed_user_auth_token()#
- Return type:
- Default:
Validates the current set user auth token and returns it
Will reauth if token is invalid
- async get_refreshed_app_token()#
- Return type:
- Default:
- get_used_token()#
Returns the currently used token, can be either the app or user auth Token or None if no auth is set
- Return type:
- Default:
- Returns:
the currently used auth token or None if no Authentication is set
- async get_extension_analytics(after=None, extension_id=None, first=20, ended_at=None, started_at=None, report_type=None)#
Gets a URL that extension developers can use to download analytics reports (CSV files) for their extensions. The URL is valid for 5 minutes.
Requires User authentication with scope
ANALYTICS_READ_EXTENSION
For detailed documentation, see here: https://dev.twitch.tv/docs/api/reference#get-extension-analytics
- Parameters:
after¶ (
Default:) –Cursor for forward pagination.
Note: The library handles pagination on its own, only use this parameter if you get a pagination cursor via other means.
Default:None
extension_id¶ (
Default:) – If this is specified, the returned URL points to an analytics report for just the specified extension.Default:None
first¶ (
Default:) –The maximum number of items to return per API call. You can use this in combination with
limit()
to optimize the bandwith and number of API calls used to fetch the amount of results you desire.Minimum 1, Maximum 100
Default:20
ended_at¶ (
Default:) – Ending date/time for returned reports, if this is provided, started_at must also be specified.Default:None
started_at¶ (
Default:) – Starting date/time for returned reports, if this is provided, ended_at must also be specified.Default:None
report_type¶ (
Default:) – Type of analytics report that is returnedDefault:None
- Raises:
UnauthorizedException – if user authentication is not set or invalid
MissingScopeException – if the user authentication is missing the required scope
TwitchAuthorizationException – if the used authentication token became invalid
TwitchAPIException – if the request was malformed and a re authentication failed
TwitchBackendException – if the Twitch API itself runs into problems
TwitchResourceNotFound – if the extension specified in extension_id was not found
ValueError – When you only supply started_at or ended_at without the other or when first is not in range 1 to 100
- Return type:
Default:- async get_game_analytics(after=None, first=20, game_id=None, ended_at=None, started_at=None, report_type=None)#
Gets a URL that game developers can use to download analytics reports (CSV files) for their games. The URL is valid for 5 minutes.
Requires User authentication with scope
ANALYTICS_READ_GAMES
For detailed documentation, see here: https://dev.twitch.tv/docs/api/reference#get-game-analytics
- Parameters:
after¶ (
Default:) –Cursor for forward pagination.
Note: The library handles pagination on its own, only use this parameter if you get a pagination cursor via other means.
Default:None
first¶ (
Default:) –The maximum number of items to return per API call. You can use this in combination with
limit()
to optimize the bandwith and number of API calls used to fetch the amount of results you desire.Minimum 1, Maximum 100
Default:20
game_id¶ (
Default:) – Game IDDefault:None
ended_at¶ (
Default:) – Ending date/time for returned reports, if this is provided, started_at must also be specified.Default:None
started_at¶ (
Default:) – Starting date/time for returned reports, if this is provided, ended_at must also be specified.Default:None
report_type¶ (
Default:) – Type of analytics report that is returned.Default:None
- Raises:
UnauthorizedException – if user authentication is not set or invalid
MissingScopeException – if the user authentication is missing the required scope
TwitchAuthorizationException – if the used authentication token became invalid and a re authentication failed
TwitchAPIException – if the request was malformed
TwitchBackendException – if the Twitch API itself runs into problems
TwitchResourceNotFound – if the game specified in game_id was not found
ValueError – When you only supply started_at or ended_at without the other or when first is not in range 1 to 100
- Return type:
Default:- async get_creator_goals(broadcaster_id)#
Gets Creator Goal Details for the specified channel.