Web/OAuth Reference¶
- asyncfetch_token
- defget_authorization_url
- asyncoauth_callback
- class twitchio.web.AiohttpAdapter(*, host: str | None = None, port: int | None = None, domain: str | None = None, eventsub_path: str | None = None, eventsub_secret: str | None = None, oauth_path: str | None = None, redirect_path: str | None = None, ssl_context: SSLContext | None = None, client: BT | None = None)¶
The AiohttpAdapter for OAuth and Webhook based EventSub.
This adapter uses
aiohttpwhich is a base dependency and should be installed and available with Twitchio.Optionally you can use Starlette with Uvicorn by using the
StarletteAdapter. This will require additional dependencies.An adapter will always be started and is ran alongside the
ClientorBotby default. You can disable starting the adapter by passingwith_adapter=Falsetotwitchio.Client.start()ortwitchio.Client.run().The adapter can be used to authenticate users via OAuth, and supports webhooks for EventSub, with in-built event dispatching to the
Client.The default callbacks for OAuth are:
/oauthE.g.http://localhost:4343/oauthorhttps://mydomain.org/oauth.- Should be used with the
?scopes=query parameter to pass a URL encoded list of scopes. See:
Scopesfor a helper class for generating scopes.
- Should be used with the
/oauth/callbackE.g.http://localhost:4343/oauth/callbackorhttps://mydomain.org/oauth/callback.The redirect URL for OAuth request. This should be set in the developer console of your application on Twitch.
The default callbacks for EventSub are:
/callbackE.g.http://localhost:4343/callbackorhttps://mydomain.org/callback.
This class handles processing and validating EventSub requests for you, and dispatches any events identical to the websocket equivalent.
- Parameters
host (str | None) – An optional
strpassed to bind as the host address. Defaults tolocalhost.port (int | None) – An optional
intpassed to bind as the port for the host address. Defaults to4343.domain (str | None) – An optional
strpassed used to identify the external domain used, if any. If passed, the domain will be used for the redirect URL in OAuth and for validation in EventSub. It must be publicly accessible and support HTTPS.eventsub_path (str | None) – An optional
strpassed to use as the path to the eventsub callback. Defaults to/callback. E.g.http://localhost:4343/callbackorhttps://mydomain.org/callback.eventsub_secret (str | None) – An optional
strpassed to use as the EventSub secret. It is recommended you pass this parameter when using an adapter for EventSub, as it will reset upon restarting otherwise. You can generate token safe secrets with thesecretsmodule.oauth_path (str | None) – An optional
strpassed to use as the path for the OAuth route. Defaults to/oauth. E.g.http://localhost:4343/oauthorhttps://mydomain.org/oauth.redirect_path (str | None) – An optional
strpassed to use as the path for the Oauth Redirect callback. Defaults to/oauth/callback. E.g.http://localhost:4343/oauth/callbackorhttps://mydomain.org/oauth/callback.ssl_context (SSLContext | None) – An optional
SSLContextpassed to the adapter. If SSL is setup via a front-facing web server such as NGINX, you should leave this as None.client (
Client| None) – An optionalClientor any derivative such asBotto set for this adapter. WhenNonethe client will be set automatically after initalization. Defaults toNone.
Examples
import twitchio from twitchio import web from twitchio.ext import commands class Bot(commands.Bot): def __init__(self) -> None: # Requests will be sent to, as an example: # http://bot.twitchio.dev # You DO NOT need to pass a domain, however not passing a domain will mean only you can authenticate # via OAuth and Webhooks will not be supported... # The domain should support HTTPS and be publicly accessible... # An easy way to do this is add your domain to a CDN like Cloudflare and set SSL to Flexible. # # Visit: http://localhost:8080/oauth?scopes=channel:bot as the broadcaster as an example. # Visit: https://bot.twitchio.dev?scopes=channel:bot as the broadcaster as an example. adapter = web.AiohttpAdapter(domain="bot.twitchio.dev", port=8080) super().__init__(adapter=adapter)
- async fetch_token(request: Request) FetchTokenPayload¶
This method handles sending the provided code to Twitch to receive a User Access and Refresh Token pair, and later, if successful, dispatches
event_oauth_authorized().To call this coroutine you should pass the request received in the
oauth_callback(). This method is called by default, however when overridingoauth_callback()you should always call this method.- Parameters
request (aiohttp.web.Request) – The request received in
oauth_callback().- Returns
The payload containing various information about the authentication request to Twitch.
- Return type
- async oauth_callback(request: Request) Response¶
Default route callback for the OAuth Authentication redirect URL.
You can override this method to alter the responses sent to the user.
This callback should always return a valid response. See: aiohttp docs for more information.
Important
You should always call
fetch_token()when overriding this method.- Parameters
request (aiohttp.web.Request) – The original request received via aiohttp.
Examples
async def oauth_callback(self, request: web.Request) -> web.Response: payload: FetchTokenPayload = await self.fetch_token(request) # Change the default success response to no content... if payload.status == 200: return web.Response(status=204) # Return the default error responses... return payload.response
- get_authorization_url(*, scopes: Scopes, force_verify: bool = False) str¶
Method used to create a OAuth URL with the given options and scopes for users to authenticate the application with.
- Parameters
scopes (
twitchio.Scopes) – Atwitchio.Scopesobject with the desired scopes.force_verify (
bool) – Aboolindicating whether the user should forcefully re-authenticate. When set to True the user must explicitly re-auth the application after visiting the URL. Defaults to False.
- Returns
The URL which can be provided to user(s) to authenticate your application.
- Return type
- Raises
ValueError – Scopes is a required parameter.
- asyncfetch_token
- defget_authorization_url
- asyncoauth_callback
- class twitchio.web.StarletteAdapter(*, host: str | None = None, port: int | None = None, domain: str | None = None, eventsub_path: str | None = None, eventsub_secret: str | None = None, oauth_path: str | None = None, redirect_path: str | None = None, ssl_keyfile: str | PathLike[str] | None = None, ssl_keyfile_password: str | None = None, ssl_certfile: str | PathLike[str] | None = None, timeout_keep_alive: int = 5, timeout_graceful_shutdown: int = 3, client: BT | None = None)¶
The StarletteAdapter for OAuth and Webhook based EventSub.
This adapter uses
starlettewhich is an optional dependency and needs to be installed.Optionally you can use Aiohttp by using the
AiohttpAdapter.An adapter will always be started and is ran alongside the
ClientorBotby default. You can disable starting the adapter by passingwith_adapter=Falsetotwitchio.Client.start()ortwitchio.Client.run().The adapter can be used to authenticate users via OAuth, and supports webhooks for EventSub, with in-built event dispatching to the
Client.The default callbacks for OAuth are:
/oauthE.g.http://localhost:4343/oauthorhttps://mydomain.org/oauth.- Should be used with the
?scopes=query parameter to pass a URL encoded list of scopes. See:
Scopesfor a helper class for generating scopes.
- Should be used with the
/oauth/callbackE.g.http://localhost:4343/oauth/callbackorhttps://mydomain.org/oauth/callback.The redirect URL for OAuth request. This should be set in the developer console of your application on Twitch.
The default callbacks for EventSub are:
/callbackE.g.http://localhost:4343/callbackorhttps://mydomain.org/callback.
This class handles processing and validating EventSub requests for you, and dispatches any events identical to the websocket equivalent.
- Parameters
host (str | None) – An optional
strpassed to bind as the host address. Defaults tolocalhost.port (int | None) – An optional
intpassed to bind as the port for the host address. Defaults to4343.domain (str | None) – An optional
strpassed used to identify the external domain used, if any. If passed, the domain will be used for the redirect URL in OAuth and for validation in EventSub. It must be publicly accessible and support HTTPS.eventsub_path (str | None) – An optional
strpassed to use as the path to the eventsub callback. Defaults to/callback. E.g.http://localhost:4343/callbackorhttps://mydomain.org/callback.eventsub_secret (str | None) – An optional
strpassed to use as the EventSub secret. It is recommended you pass this parameter when using an adapter for EventSub, as it will reset upon restarting otherwise. You can generate token safe secrets with thesecretsmodule.oauth_path (str | None) – An optional
strpassed to use as the path for the OAuth route. Defaults to/oauth. E.g.http://localhost:4343/oauthorhttps://mydomain.org/oauth.redirect_path (str | None) – An optional
strpassed to use as the path for the Oauth Redirect callback. Defaults to/oauth/callback. E.g.http://localhost:4343/oauth/callbackorhttps://mydomain.org/oauth/callback.ssl_keyfile (str | PathLike[str] | None) – An optional SSL key file passed to Uvicorn.
ssl_keyfile_password (str | None) – An optional password to decrypt the ssl key, passed to Uvicorn.
ssl_certfile (str | PathLike[str] | None) – An optional SSL certificate file, passed to Uvicorn.
timeout_keep_alive (int) – An optional
intwhich is the maximum amount of time in secondsUvicornshould wait before closing Keep-Alive connections. Defaults to5.timeout_graceful_shutdown (int) – An optional
intwhich is the maximum amount of time in secondsUvicornshould wait before forcefully closing. Defaults to3.client (
Client| None) – An optionalClientor any derivative such asBotto set for this adapter. WhenNonethe client will be set automatically after initalization. Defaults toNone.
Examples
import twitchio from twitchio import web from twitchio.ext import commands class Bot(commands.Bot): def __init__(self) -> None: # Requests will be sent to, as an example: # http://bot.twitchio.dev # You DO NOT need to pass a domain, however not passing a domain will mean only you can authenticate # via OAuth and Webhooks will not be supported... # The domain should support HTTPS and be publicly accessible... # An easy way to do this is add your domain to a CDN like Cloudflare and set SSL to Flexible. # # Visit: http://localhost:8080/oauth?scopes=channel:bot as the broadcaster as an example. # Visit: https://bot.twitchio.dev?scopes=channel:bot as the broadcaster as an example. adapter = web.StarletteAdapter(domain="bot.twitchio.dev", port=8080) super().__init__(adapter=adapter)
- async fetch_token(request: Request) FetchTokenPayload¶
This method handles sending the provided code to Twitch to receive a User Access and Refresh Token pair, and later, if successful, dispatches
event_oauth_authorized().To call this coroutine you should pass the request received in the
oauth_callback(). This method is called by default, however when overridingoauth_callback()you should always call this method.- Parameters
request (starlette.requests.Request) – The request received in
oauth_callback().- Returns
The payload containing various information about the authentication request to Twitch.
- Return type
- async oauth_callback(request: Request) Response¶
Default route callback for the OAuth Authentication redirect URL.
You can override this method to alter the responses sent to the user.
This callback should always return a valid response. See: Starlette Responses for available response types.
Important
You should always call
fetch_token()when overriding this method.- Parameters
request (starlette.requests.Request) – The original request received via Starlette.
Examples
async def oauth_callback(self, request: Request) -> Response: payload: FetchTokenPayload = await self.fetch_token(request) # Change the default success response... if payload.status == 200: return HTMLResponse(status_code=200, "<h1>Success!</h1>") # Return the default error responses... return payload.response
- get_authorization_url(*, scopes: Scopes, force_verify: bool = False) str¶
Method used to create a OAuth URL with the given options and scopes for users to authenticate the application with.
- Parameters
scopes (
twitchio.Scopes) – Atwitchio.Scopesobject with the desired scopes.force_verify (
bool) – Aboolindicating whether the user should forcefully re-authenticate. When set to True the user must explicitly re-auth the application after visiting the URL. Defaults to False.
- Returns
The URL which can be provided to user(s) to authenticate your application.
- Return type
- Raises
ValueError – Scopes is a required parameter.
Models and Payloads¶
- class twitchio.web.FetchTokenPayload¶
Payload model returned via
twitchio.web.StarletteAdapter.fetch_token()andtwitchio.web.AiohttpAdapter.fetch_token()- status¶
The status code returned while trying to authenticate a user on Twitch. A status of
200indicates a success.- Type
- response¶
The response TwitchIO sends by default to the user after trying to authenticate via OAuth.
- Type
web.Response | starlette.responses.Response
- payload¶
The payload received from Twitch when a user successfully authenticates via OAuth. Will be
Noneif a non200status code is returned.
- exception¶
The exception raised while trying to authenticate a user. Could be
Noneif no exception occurred.- Type
twitchio.HTTPException| None
Documentation