Migrating¶
Warning
This document is large and currently an active 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,heartbeatandretain_cache.TwitchIO 3 uses a much more modern asyncio design which results in the removal of any
loopsemantics including the constructor parameterloop. Internally the start and close of the bot has also been changed, resulting in a more user-friendly interface.App Tokensare 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 theClientafterloginbut before theClientstarts completely.EventSub is fully managed on the
Client. See:subscribe_websocket()andsubscribe_webhook().fetch_*methods no longer accept atokenparameter. Instead you can passtoken_forwhich is theuser IDof 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.HTTPAsyncIteratorfor ease of use.
Added:
Parameter
bot_idParameter
redirect_uriParameter
scopesParameter
sessionParameter
adapterParameter
fetch_client_user
Changed:
twitchio.Client.wait_for()predicateandtimeoutare now both keyword-only arguments.predicateis now async.
Client.wait_for_readyis nowtwitchio.Client.wait_until_ready()Client.create_useris nowtwitchio.Client.create_partialuser()Client.fetch_chatters_colorsis nowfetch_chatters_color()Client.fetch_content_classification_labelsis nowfetch_classifications()
Removed:
Client parameter
initial_channelsClient parameter
heartbeatClient parameter
retain_cacheClient parameter
loopClient.connected_channelsClient.loopClient.nickClient.user_idClient.eventsClient.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()
Conduits and AutoClient/Bot¶
Recently Twitch added the Conduit transport type. Conduits help separate your EventSub subscriptions from the underlying
connection/transport (Websocket/Webhook) and load balances the events sent between them.
Read more about Conduits on the Twitch Docs .
Conduits come with some advantages over traditional EventSub:
Uses App Access Tokens (Not User Tokens)
Subscription Continuity (Subscriptions remain on the Conduit even if the Bot and all it’s connections disconnect for upto 72 hours)
Load balancing between connections
Scale up and down easily
Less subscription limits
In TwitchIO V3 we support Conduits in two forms:
Your own implementation using the Models and API.
We highly recommended using Conduits in-place of the regular EventSub implementation for your application. The easiest way to get
started is with twitchio.AutoClient and twitchio.ext.commands.AutoBot.
Added:
Cache and Channels¶
Previous versions of TwitchIO used caching mechanisms to store "Connected Channels" and the "Chatters" associated with those channels.
Due to the removal of IRC this is no longer necessary and TwitchIO only does very limited caching where needed.
EventSub events that have an associated channel will contain a broadcaster attribute which is a twitchio.PartialUser,
and is the channel the event originates from and can be used to perform actions on the channel/broadcaster.
If you are using a Command, a RewardCommand or anywhere
Context is available, consider using the helper methods and attributes available on
Context.
Removed:
Client.connected_channelsClient.get_channel()
Twitch Identifiers¶
Twitch identifiers (ID’s) have been changed from int’s to str’s. This is inline with the data provided by Twitch.
Twitch can not make any guarantees that in the future the format of ID’s which can currently be converted to a int
won’t change. For this reason instead of risking a library breaking bug being introduced via the API (in the small chance the format does change)
the type of all identifiers will remain strings.
Any .id attribute on a Twitch Model will be a str.
User, PartialUser and Chatters¶
TODO
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,
payloadorContext, 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:
predicateandtimeoutare now both keyword-only arguments.predicateis 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()predicateandtimeoutare now both keyword-only arguments.predicateis now async.
Client.wait_for_readyis nowtwitchio.Client.wait_until_ready()
PubSub Ext¶
Twitch removed support for PubSub. You can read more on this blog post .
Sounds Ext¶
The sounds extension has been removed and will be replaced with an Overlays extension in a future release.
Routines Ext¶
The way you use Routines has not changed significantly, with only one difference. You can no longer provide the seconds, minutes, hours etc
arguments and instead pass a datetime.timedelta in their place.
Besides this change, Routines mostly underwent optimizations and compatability with asyncio changes.
Added:
Changed:
twitchio.ext.routines.routine()Accepts a
datetime.timedeltain place of individual units.
twitchio.ext.routines.Routine.change_interval()Accepts a
datetime.timedeltain place of individual units.
Removed:
Attribute
Routine.start_time.
Changelog¶
Environment¶
Python:
Minimum Python version changed from
3.7to3.11.
Dependencies:
Bumped
aiohttpminimum version to3.9.1Added Optional
[starlette]Added Optional
[docs](For developing the documentation)Added Optional
[dev](Required tools for development)Removed
iso8601Removed
typing-extensionsRemoved Optional
[sounds]Removed Optional
[speed]
Library Revisions¶
General:
- Twitch Identifiers (ID’s) are now represented as str. Previously an int.
Added¶
Conduits:
twitchio.
Adapters:
Client:
Parameter
bot_idParameter
redirect_uriParameter
scopesParameter
sessionParameter
adapterParameter
fetch_client_user
Utils/Helpers:
twitchio.Color(An alias totwitchio.Colour)
Events:
EventSub Subscriptions:
Routines:
Changed¶
Client:
twitchio.Client.wait_for()predicateandtimeoutare now both keyword-only arguments.predicateis now async.
Client.wait_for_readyis nowtwitchio.Client.wait_until_ready()Client.create_useris nowtwitchio.Client.create_partialuser()Client.fetch_chatters_colorsis nowfetch_chatters_color()Client.fetch_content_classification_labelsis nowfetch_classifications()
Routines:
twitchio.ext.routines.routine()Accepts a
datetime.timedeltain place of individual units.
twitchio.ext.routines.Routine.change_interval()Accepts a
datetime.timedeltain place of individual units.
Removed¶
twitchio.ext.pubsubTwitch no longer supports PubSub.
IRCSee: FAQ for more information.
Client:
Client parameter
initial_channelsClient parameter
heartbeatClient parameter
retain_cacheClient parameter
loopClient.connected_channelsClient.loopClient.nickClient.user_idClient.eventsClient.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()
Routines:
Attribute
Routine.start_time.
TwitchIO - Documentation