Migrating¶
Warning
This document is a work in progress.
Version 2 to version 3 has many breaking changes, new systems, new implementations and new designs that will require rewriting any existing applications. Some of these changes will feel similar (such as ext.commands), while others have been completely removed (such as IRC, see: FAQ), or are new or significantly changed. This document serves to hopefully make it easier to move over to version 3.
Python Version Changes¶
TwitchIO version 3 uses a minimum Python version of 3.11
. See: Installing for more information.
Token Management and OAuth¶
One of the main focuses of version 3 was to make it easier for developers to manage authentication tokens.
When starting or restarting the twitchio.Client
a new App Token
is automatically (re)generated. This behaviour can be
changed by passing an App Token
to start()
, run()
or login()
however since there are no ratelimits on this endpoint, it is generally safer and easier to use the deafult.
The following systems have been added to help aid in token management in version 3:
Web Adapters:
Client:
Events:
Scopes:
By default a web adapter is started and ran alongside your application when it starts. The web adapters are ready with batteries-included to handle OAuth and EventSub via webhooks.
The default redirect URL for OAuth is http://localhost:4343/oauth/callback
which can be added to your application in the Twitch Developer Console. You can then
visit http://localhost:4343/oauth?scopes=
with a list of provided scopes to authenticate and add the User Token
to the
Client
.
After closing the Client
gracefully, all tokens currently managed will be
saved to a file named .tio.tokens.json
. This same file is also read and loaded when the Client
starts.
Consider reading the Quickstart Guide for an example on this flow, and implementing a SQL Database as an alternative for token storage.
Internally version 3 also implements a Managed HTTPClient which handles validating and refreshing loaded tokens automatically.
Another benefit of the Managed HTTPClient is it attempts to find and use the appropriate token for each request, unless explicitly
overriden, which can be done on most on methods that allow it via the token_for
or token
parameters.
Running a Client/Bot¶
Running a Client
or Bot
hasn’t changed much since version 2, however there are
some major differences that should be taken into consideration:
IRC was removed from the core of TwitchIO. This means subscribing to chat and other chat related events is now done via
EventSub
. This results in the removal of constructor parametersinitial_channels
,heartbeat
andretain_cache
.TwitchIO 3 uses a much more modern asyncio design which results in the removal of any
loop
semantics including the constructor parameterloop
. Internally the start and close of the bot has also been changed, resulting in a more user-friendly interface.App Tokens
are generated automatically on start-up and there is rarely a need to provide one. However the option still exists viastart()
andlogin()
.Implemented
__aenter__
and__aexit__
which allows them to be used in a Async Context Manager for easier management of close down and cleanup. These changes along with some async internals have also been reflected inrun()
.
You can also login()
the Client
without running a continuous asyncio event loop, E.g.
for making HTTP Requests only or for using the Client
in an already running event loop.
However we recommend following the below as a simple and modern way of starting your Client/Bot:
import asyncio
...
if __name__ == "__main__":
async def main() -> None:
twitchio.utils.setup_logging()
async with Bot() as bot:
await bot.start()
try:
asyncio.run(main())
except KeyboardInterrupt:
...
In addition to the above changes, the Client
has undergone other various changes:
Added the
setup_hook()
callback which allows async setup on theClient
afterlogin
but before theClient
starts completely.EventSub is fully managed on the
Client
. See:subscribe_websocket()
andsubscribe_webhook()
.fetch_*
methods no longer accept atoken
parameter. Instead you can passtoken_for
which is theuser ID
of the token you wish to use. However this is rarely needed as TwitchIO will select the most appropriate token for the call.Some
fetch_*
methods which require pagination return atwitchio.HTTPAsyncIterator
for ease of use.
Added:
Parameter
bot_id
Parameter
redirect_uri
Parameter
scopes
Parameter
session
Parameter
adapter
Parameter
fetch_client_user
Changed:
twitchio.Client.wait_for()
predicate
andtimeout
are now both keyword-only arguments.predicate
is now async.
Client.wait_for_ready
is nowtwitchio.Client.wait_until_ready()
Client.create_user
is nowtwitchio.Client.create_partialuser()
Client.fetch_chatters_colors
is nowfetch_chatters_color()
Client.fetch_content_classification_labels
is nowfetch_classifications()
Removed:
Client parameter
initial_channels
Client parameter
heartbeat
Client parameter
retain_cache
Client parameter
loop
Client.connected_channels
Client.loop
Client.nick
Client.user_id
Client.events
Client.connect()
Client.event_channel_join_failure()
Client.event_channel_joined()
Client.event_join()
Client.event_mode()
Client.event_notice()
Client.event_part()
Client.event_raw_data()
Client.event_raw_notice()
Client.event_raw_usernotice()
Client.event_reconnect()
Client.event_token_expired()
Client.event_usernotice_subscription()
Client.event_userstate()
Client.get_channel()
Client.get_webhook_subscriptions()
Client.join_channels()
Client.part_channels()
Client.update_chatter_color()
Client.from_client_credentials()
Client.fetch_global_chat_badges()
Client.fetch_global_emotes()
Logging¶
Version 3 adds a logging helper which allows for a simple and easier way to setup logging formatting for your application.
As version 3 uses logging heavily and encourages developers to use logging in place of print
statements where appropriate
we would encourage you to call this function. Usually you would call this helper before starting the client for each logger.
If you are calling this on the root
logger (default), you should only need to call this function once.
Added:
Assets and Colours¶
In version 2, all images, colour/hex codes and other assets were usually just strings of the hex or a URL pointing to the asset.
In version 3 all assets are now a special class twitchio.Asset
which can be used to download, save and manage
the various assets available from Twitch such as twitchio.Game.box_art
.
Any colour that Twitch returns as a valid HEX or RGB code is also a special class twitchio.Colour
. This class
implements various dunders such as __format__
which will help in using the Colour
in strings,
other helpers to convert the colour data to different formats, and classmethod helpers to retrieve default colours.
Added:
twitchio.Color
(An alias totwitchio.Colour
)
HTTP Async Iterator¶
In previous versions all requests made to Twitch were made in a single call and did not have an option to paginate.
With version 3 you will notice paginated endpoints now return a twitchio.HTTPAsyncIterator
. This class is a async
iterator which allows the following semantics:
await method(...)
or
async for item in method(...)
This allows fetching a flattened list of the first page of results only (await
) or making paginated requests as an iterator
(async for
).
You can flatten a paginated request by using a list comprehension.
# Flatten and return first page (20 results)
streams = await bot.fetch_streams()
# Flatten and return up to 1000 results (max 100 per page) which equates to 10 requests...
streams = [stream async for stream in bot.fetch_streams(first=100, max_results=1000)]
# Loop over results until we manually stop...
async for item in bot.fetch_streams(first=100, max_results=1000):
# Some logic...
...
break
Twitch endpoints only allow a max of 100
results per page, with a default of 20
.
You can identify endpoints which support the twitchio.HTTPAsyncIterator
by looking for the following on top of the
function in the docs:
async for item in .endpoint(...):
Added:
Events¶
Events in version 3 have changed internally, however user facing should be fairly similar. One main difference to note
is that all events accept exactly one argument, a payload containing relevant event data, with the exception of
twitchio.event_ready()
which accepts exactly 0
arguments, and some command events which accept
twitchio.ext.commands.Context
only.
For a list of events and their relevant payloads see the Event Reference.
Changed:
Events now accept a single argument,
payload
orContext
, with one exception (twitchio.event_ready()
).
Wait For¶
twitchio.Client.wait_for()
has changed internally however should act similiary to previous versions with some notes:
predicate
andtimeout
are now both keyword-only arguments.predicate
is now async.
twitchio.Client.wait_for()
returns the payload of the waiting event.
To wait until the bot is ready, consider using twitchio.Client.wait_until_ready()
.
Changed:
twitchio.Client.wait_for()
predicate
andtimeout
are now both keyword-only arguments.predicate
is now async.
Client.wait_for_ready
is nowtwitchio.Client.wait_until_ready()
Changelog¶
Environment¶
Python:
Minimum Python version changed from
3.7
to3.11
.
Dependencies:
Bumped
aiohttp
minimum version to3.9.1
Added Optional
[starlette]
Added Optional
[docs]
(For developing the documentation)Added Optional
[dev]
(Required tools for development)Removed
iso8601
Removed
typing-extensions
Removed Optional
[sounds]
Removed Optional
[speed]
Added¶
Client:
Parameter
bot_id
Parameter
redirect_uri
Parameter
scopes
Parameter
session
Parameter
adapter
Parameter
fetch_client_user
Utils/Helpers:
twitchio.Color
(An alias totwitchio.Colour
)
Events:
Changed¶
Client:
twitchio.Client.wait_for()
predicate
andtimeout
are now both keyword-only arguments.predicate
is now async.
Client.wait_for_ready
is nowtwitchio.Client.wait_until_ready()
Client.create_user
is nowtwitchio.Client.create_partialuser()
Client.fetch_chatters_colors
is nowfetch_chatters_color()
Client.fetch_content_classification_labels
is nowfetch_classifications()
Removed¶
twitchio.ext.pubsub
Twitch no longer supports PubSub.
IRC
See: FAQ for more information.
Client:
Client parameter
initial_channels
Client parameter
heartbeat
Client parameter
retain_cache
Client parameter
loop
Client.connected_channels
Client.loop
Client.nick
Client.user_id
Client.events
Client.connect()
Client.event_channel_join_failure()
Client.event_channel_joined()
Client.event_join()
Client.event_mode()
Client.event_notice()
Client.event_part()
Client.event_raw_data()
Client.event_raw_notice()
Client.event_raw_usernotice()
Client.event_reconnect()
Client.event_token_expired()
Client.event_usernotice_subscription()
Client.event_userstate()
Client.get_channel()
Client.get_webhook_subscriptions()
Client.join_channels()
Client.part_channels()
Client.update_chatter_color()
Client.from_client_credentials()
Client.fetch_global_chat_badges()
Client.fetch_global_emotes()