Web/OAuth Reference

Methods
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, ssl_context: SSLContext | None = None)

The AiohttpAdapter for OAuth and Webhook based EventSub.

This adapter uses aiohttp which 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 Client or Bot by default. You can disable starting the adapter by passing with_adapter=False to twitchio.Client.start() or twitchio.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:

  • /oauth E.g. http://localhost:4343/oauth or https://mydomain.org/oauth.
    • Should be used with the ?scopes= query parameter to pass a URL encoded list of scopes.

      See: Scopes for a helper class for generating scopes.

  • /oauth/callback E.g. http://localhost:4343/oauth/callback or https://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:

  • /callback E.g. http://localhost:4343/callback or https://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 str passed to bind as the host address. Defaults to localhost.

  • port (int | None) – An optional int passed to bind as the port for the host address. Defaults to 4343.

  • domain (str | None) – An optional str passed 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 str passed to use as the path to the eventsub callback. Defaults to /callback. E.g. http://localhost:4343/callback or https://mydomain.org/callback.

  • eventsub_secret (str | None) – An optional str passed 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 the secrets module.

  • ssl_context (SSLContext | None) – An optional SSLContext passed to the adapter. If SSL is setup via a front-facing web server such as NGINX, you should leave this as None.

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)
property eventsub_url: str

Property returning the fully qualified URL to the EventSub callback.

property redirect_url: str

Property returning the fully qualified URL to the OAuth callback.

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 overriding oauth_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

FetchTokenPayload

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
Methods
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)

The StarletteAdapter for OAuth and Webhook based EventSub.

This adapter uses starlette which 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 Client or Bot by default. You can disable starting the adapter by passing with_adapter=False to twitchio.Client.start() or twitchio.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:

  • /oauth E.g. http://localhost:4343/oauth or https://mydomain.org/oauth.
    • Should be used with the ?scopes= query parameter to pass a URL encoded list of scopes.

      See: Scopes for a helper class for generating scopes.

  • /oauth/callback E.g. http://localhost:4343/oauth/callback or https://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:

  • /callback E.g. http://localhost:4343/callback or https://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 str passed to bind as the host address. Defaults to localhost.

  • port (int | None) – An optional int passed to bind as the port for the host address. Defaults to 4343.

  • domain (str | None) – An optional str passed 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 str passed to use as the path to the eventsub callback. Defaults to /callback. E.g. http://localhost:4343/callback or https://mydomain.org/callback.

  • eventsub_secret (str | None) – An optional str passed 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 the secrets module.

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)
property eventsub_url: str

Property returning the fully qualified URL to the EventSub callback.

property redirect_url: str

Property returning the fully qualified URL to the OAuth callback.

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 overriding oauth_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

FetchTokenPayload

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

Models and Payloads

class twitchio.web.FetchTokenPayload

Payload model returned via twitchio.web.StarletteAdapter.fetch_token() and twitchio.web.AiohttpAdapter.fetch_token()

status

The status code returned while trying to authenticate a user on Twitch. A status of 200 indicates a success.

Type

int

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 None if a non 200 status code is returned.

Type

twitchio.authentication.UserTokenPayload

exception

The exception raised while trying to authenticate a user. Could be None if no exception occurred.

Type

twitchio.HTTPException | None

class twitchio.authentication.UserTokenPayload

OAuth model received when a user successfully authenticates your application on Twitch.

This is a raw container class.

access_token

The user access token.

Type

str

refresh_token

The user refresh token for this access token.

Type

str

expires_in

The amount of time this token is valid before expiring as seconds.

Type

int

scope

A str or list[str] containing the scopes the user authenticated with.

Type

str | list[str]

token_type

The type of token provided. Usually bearer.

Type

str