Common models reference#

This page contains all of the most common classes and models you’ll see when developing with twitchio.

class twitchio.PartialUser(http: HTTPHandler, id: int | str, name: str | None)#

A minimal representation of a user on twitch. This class allows you to perform operations using the Twitch API, targeting channels and users.

Changed in version 3.0.

id#

The id of the user.

Type

int

name#

The name of the user (this corresponds to the login field of the API).

Type

str | None

coroutine automod_check(query: list[twitchio.models.AutomodCheckMessage]) list[twitchio.models.AutomodCheckResponse]#

This function is a coroutine.

Checks if a string passes the automod filter. Requires an OAuth token with the moderation:read scope.

Parameters

query (list[AutomodCheckMessage]) – A list of :class:`AutomodCheckMessage`s.

Return type

list[AutomodCheckResponse]

coroutine create_clip(has_delay=False) dict#

This function is a coroutine.

Creates a clip on the channel. Note that clips are not created instantly, so you will have to query get_clips() to confirm the clip was created. Requires an OAuth token with the clips:edit scope

Parameters

has_delay (bool) – Whether the clip should have a delay to match that of a viewer. Defaults to False

Return type

dict a dictionary with id and edit_url

coroutine create_marker(description: str | None = None) Marker#

This function is a coroutine.

Creates a marker on the stream. This only works if the channel is live (among other conditions). Requires an OAuth token with the user:edit:broadcast scope.

Parameters

description (str) – An optional description of the marker

Return type

Marker

coroutine create_poll(title: str, choices: list[str], duration: int, bits_voting_enabled: bool = False, bits_per_vote: int | None = None, channel_points_voting_enabled: bool | None = False, channel_points_per_vote: int | None = None) Poll#

This function is a coroutine.

Creates a poll for the specified channel/broadcaster. Requires an OAuth token with the channel:manage:polls scope.

Parameters
  • title (str) – Question displayed for the poll.

  • choices (list[str]) – List of choices for the poll. Must be between 2 and 5 choices.

  • duration (int) – Total duration for the poll in seconds. Must be between 15 and 1800.

  • bits_voting_enabled (bool | None) – Indicates if Bits can be used for voting. Default is False.

  • bits_per_vote (int | None) – Number of Bits required to vote once with Bits. Max 10000.

  • channel_points_voting_enabled (bool) – Indicates if Channel Points can be used for extra votes. Default is False.

  • channel_points_per_vote (int | None) – Number of Channel Points required to vote once with Channel Points. Max 1000000.

Return type

twitchio.Poll

coroutine create_prediction(title: str, outcomes: list[str], prediction_window: int) Prediction#

This function is a coroutine.

Creates a prediction for the channel. Requires an OAuth token with the channel:manage:predictions scope.

Changed in version 3.0.

Parameters
  • title (str) – Title for the prediction (max of 45 characters)

  • outcomes (list[str]) – The available outcomes for the prediction. There must be between 2 and 10 outcomes, each may contain up to 25 characters.

  • prediction_window (int) – Total duration for the prediction (in seconds). Minimum 30 and maximum 1800 (30 minutes).

Return type

twitchio.Prediction

coroutine edit(description: str) None#

This function is a coroutine.

Edits a channels description.

Parameters

description (str) – The new description for the user.

coroutine end_poll(poll_id: str, status: Literal['TERMINATED', 'ARCHIVED'])#

This function is a coroutine.

Ends a poll for the specified channel/broadcaster. Requires an OAuth token with the channel:manage:polls scope.

Parameters
  • poll_id (str) – ID of the poll.

  • status (str) – The poll status to be set. Valid values: TERMINATED: End the poll manually, but allow it to be viewed publicly. ARCHIVED: End the poll manually and do not allow it to be viewed publicly.

Return type

twitchio.Poll

coroutine end_prediction(prediction_id: str, status: Literal['RESOLVED', 'CANCELED', 'LOCKED'], winning_outcome_id: str | None = None) Prediction#

This function is a coroutine.

End a prediction with an outcome. If you lock the prediction, you may call this method again to update the status to resolved or canceled. Requires an OAuth token with the channel:manage:predictions scope.

Changed in version 3.0.

Parameters
  • prediction_id (str) – ID of the prediction to end.

  • status (str) – The status of the prediction. Must be one of RESOLVED, CANCELED, or LOCKED. Once the status is set to locked, you have 24 hours to update the status to RESOLVED, or twitch will cancel the prediction, and return the points.

  • winning_outcome_id (str | None) – The outcome id that wins the prediction. This must be set if status is set to RESOLVED.

Return type

Prediction

coroutine fetch(use_client_token: bool = False) User#

This function is a coroutine.

Fetches the full user from the api.

Parameters

use_client_token (bool) – Whether to use the client token or to fetch this user using their own token. If you do not have access to this user’s token, you should set this to True. Defaults to False.

Return type

User The full user associated with this PartialUser

coroutine fetch_active_extensions(use_app_token: bool = False) ActiveExtensionType#

This function is a coroutine.

Fetches active extensions the user has. Returns a dictionary containing the following keys: panel, overlay, component.

May require an OAuth token with the user:read:broadcast or user:edit:broadcast scope.

Changed in version 3.0.

Parameters

use_app_token (bool) – Whether to use an app access token, or use a user OAuth token. Defaults to False.

Return type

dict[Literal[“panel”, “overlay”, “component”], dict[int, ActiveExtension]]

fetch_ban_events(userids: list[int] | None = None) HTTPAwaitableAsyncIterator[BanEvent]#

This function returns an awaitable async iterator.

Fetches ban/unban events from the User’s channel. Requires an OAuth token with the moderation:read scope.

Changed in version 3.0.

Parameters

userids (list[int] | None) – An optional list of users to fetch ban/unban events for. If not passed, all events will be fetched.

Return type

AwaitableAsyncIterator`[:class:`BanEvent]

fetch_bans(userids: list[str | int] | None = None) HTTPAwaitableAsyncIterator[UserBan]#

This function returns an awaitable async iterator.

Fetches a list of people the User has banned from their channel. Requires an OAuth token with the moderation:read scope.

Changed in version 3.0.

Parameters

userids (list[Union[str, int]] | None) – An optional list of userids to fetch. Will fetch all bans if this is not passed.

Return type

AwaitableAsyncIterator`[:class:`UserBan]

coroutine fetch_bits_leaderboard(period: Literal['all', 'day', 'week', 'month', 'year'] = 'all', user_id: int | None = None, started_at: datetime.datetime | None = None) BitsLeaderboard#

This function is a coroutine.

Fetches the bits leaderboard for the channel. Requires an OAuth token with the bits:read scope.

Changed in version 3.0.

Parameters
  • period (Optional[str]) – one of day, week, month, year, or all, defaults to all.

  • user_id (Optional[int]) – the id of the user to fetch for.

  • started_at (Optional[datetime.datetime]) – the timestamp to start the period at. This is ignored if the period is all.

Return type

BitsLeaderboard

fetch_channel_followers(target: BaseUser, user_id: int | None = None) HTTPAwaitableAsyncIterator[ChannelFollowerEvent]#

This function returns an awaitable async iterator.

Fetches a list of users that are following this user. Requires an OAuth token with the moderator:read:followers scope.

Changed in version 3.0.

Parameters
  • target (BaseUser) – The BaseUser with the user ID of which token you are using with appropriate scopes.

  • user_id (int | None) – Optional user ID to check whether this specific user is following the broadcaster.

Return type

AwaitableAsyncIterator`[:class:`ChannelFollowerEvent]

coroutine fetch_channel_followers_count() int#

This function is a coroutine.

Fetches total number of channels that follows this user. Requires an OAuth token with the user:read:follows scope.

Changed in version 3.0.

Return type

int

fetch_channel_following(target: BaseUser, broadcaster_id: int | None = None) HTTPAwaitableAsyncIterator[ChannelFollowingEvent]#

This function returns an awaitable async iterator.

Fetches a list of users that this user is following. Requires an OAuth token with the user:read:follows scope.

Changed in version 3.0.

Parameters
  • target (BaseUser) – The BaseUser with the user ID of which token you are using with appropriate scopes.

  • broadcaster_id (int | None) – Optional broadcaster / user ID to check whether the user follows this specified broadcaster.

Return type

AwaitableAsyncIterator`[:class:`ChannelFollowingEvent]

coroutine fetch_channel_following_count(target: BaseUser) int#

This function is a coroutine.

Fetches total number of channels that this user is following.

Changed in version 3.0.

Parameters

target (BaseUser) – The BaseUser with the user ID of which token you are using with appropriate scopes.

Return type

int

coroutine fetch_channel_teams(use_app_token: bool = False) list[twitchio.models.ChannelTeams]#

This function is a coroutine.

Fetches a list of Twitch Teams of which the specified channel/broadcaster is a member.

Changed in version 3.0.

Parameters

use_app_token (bool) – Whether to use an app access token, or use a user OAuth token. Defaults to False.

Return type

list[twitchio.ChannelTeams]

coroutine fetch_chat_settings(moderator: twitchio.models.BaseUser | None = None) ChatSettings#

This function is a coroutine.

Fetches the current chat settings for the channel.

Changed in version 3.0.

Parameters

moderator (BaseUser | None) – A moderator to fetch the chat settings as. Setting this will attempt to fetch the request using the moderators token, otherwise the broadcasters will be used.

Return type

ChatSettings

fetch_clips(started_at: datetime.datetime | None = None, ended_at: datetime.datetime | None = None, is_featured: bool | None = None) HTTPAwaitableAsyncIterator[Clip]#

This function returns an awaitable async iterator.

Fetches clips from the api. This will only return clips created by this user. Use fetch_clips() to fetch clips by id

Changed in version 3.0.

Return type

Clip]

fetch_custom_rewards(*, only_manageable=False, ids: list[int] | None = None, force=False) HTTPAwaitableAsyncIterator[CustomReward]#

This function returns an awaitable async iterator.

Fetches the channels custom rewards (aka channel points) from the api. Requires an OAuth token with the channel:read:redemptions or channel:manage:redemptions scope.

Changed in version 3.0.

Parameters
  • only_manageable (bool) – Whether to fetch all rewards or only ones you can manage. Defaults to false.

  • ids (list[int]) – An optional list of reward ids.

  • force (bool) – Whether to force a fetch or try to get from cache. Defaults to False.

Return type

CustomReward]

coroutine fetch_extensions() list[twitchio.models.Extension]#

This function is a coroutine.

Fetches extensions the user has (active and inactive). Requires an OAuth token with the user:read:broadcast or user:edit:broadcast scope. * To include inactive extensions, you must have the user:edit:broadcast scope.

Return type

list[Extension]

coroutine fetch_goals() list[twitchio.models.Goal]#

This function is a coroutine.

Fetches a list of goals for the channel. Requires an OAuth token with the user:read:broadcast scope.

Changed in version 3.0.

Return type

list[twitchio.Goal]

fetch_hypetrain_events(id: str | None = None) HTTPAwaitableAsyncIterator[HypeTrainEvent]#

This function returns an awaitable async iterator.

Fetches hypetrain event from the api. Requires a token with the channel:read:hype_train scope.

Changed in version 3.0.

Parameters

id (str | None) – The hypetrain id, if known, to fetch for.

Return type

HypeTrainEvent]

coroutine fetch_markers(video_id: str | None = None) HTTPAwaitableAsyncIterator[tuple[twitchio.models.PartialUser, twitchio.models.VideoMarkers]]#

This function returns an awaitable async iterator.

Fetches markers from the given video id, or the most recent video. The Twitch api will only return markers created by the user of the authorized token. Requires an OAuth token with the user:read:broadcast or channel:manage:broadcast scope.

Changed in version 3.0.

Parameters

video_id (str) – A specific video to fetch from. Defaults to the most recent stream if not passed. If this is not the users own video, they must be an editor on the users channel.

Return type

AwaitableAsyncIterator`[tuple[:class:`PartialUser, twitchio.VideoMarkers]]

fetch_mod_events() HTTPAwaitableAsyncIterator[ModEvent]#

This function is a coroutine.

Fetches mod events (moderators being added and removed) for this channel. Requires an OAuth token with the moderation:read scope.

Changed in version 3.0.

Return type

ModEvent]

fetch_moderators(userids: list[int] | None = None) HTTPAwaitableAsyncIterator[PartialUser]#

This function returns an awaitable async iterator.

Fetches the moderators for this channel. Requires an OAuth token with the moderation:read scope.

Changed in version 3.0.

Parameters

userids (list[int] | None) – An optional list of users to check mod status of. If not passed, all mods will be fetched.

Return type

AwaitableAsyncIterator`[:class:`PartialUser]

fetch_polls(poll_ids: list[str] | None = None) HTTPAwaitableAsyncIterator[Poll]#

This function returns an awaitable async iterator.

Fetches a list of polls for the specified channel/broadcaster. Requires an OAuth token with the channel:read:polls or channel:manage:polls scope. Polls are available for 90 days after being created.

Changed in version 3.0.

Parameters

poll_ids (list[str] | None) – List of poll IDs to return. Maximum: 100

Return type

Poll]

fetch_schedule(segment_ids: list[str] | None = None, start_time: datetime.datetime | None = None, use_app_token: bool = False) HTTPAwaitableAsyncIterator[Schedule]#

This function returns an awaitable async iterator.

Fetches the channel schedule.

Changed in version 3.0.

Parameters
  • segment_ids (list[str] | None) – List of segment IDs of the stream schedule to return. Maximum: 100

  • start_time (datetime.datetime | None) – A datetime object to start returning stream segments from. If not specified, the current date and time is used.

Return type

Schedule]

coroutine fetch_stream_key() str#

This function is a coroutine.

Fetches the users stream key. Requires an OAuth token with the channel:read:stream_key scope.

Changed in version 3.0.

Return type

str

coroutine fetch_subscribed_to(to_user: BaseUser) twitchio.models.SubscribedEvent | None#

This function is a coroutine.

Fetches the subscriptions for this channel. Requires an OAuth token with the user:read:subscriptions scope.

Changed in version 3.0.

Return type

twitchio.SubscribedEvent | None

fetch_subscribers(target: BaseUser, userids: list[int] | None = None) HTTPAwaitableAsyncIterator[SubscriptionEvent]#

This function returns an awaitable async iterator.

Fetches the subscriptions for this channel. Requires an OAuth token with the channel:read:subscriptions scope.

Changed in version 3.0.

Parameters

userids (list[int] | None) – An optional list of userids to look for

Return type

SubscriptionEvent]

coroutine fetch_tags() list[twitchio.models.Tag]#

This function is a coroutine.

Fetches tags the user currently has active.

Return type

list[Tag]

fetch_videos(period: Literal['all', 'day', 'week', 'month'] = 'all', sort: Literal['time', 'trending', 'views'] = 'time', type: Literal['upload', 'archive', 'highlight', 'all'] = 'all', use_app_token: bool = False) HTTPAwaitableAsyncIterator[Video]#

This function returns an awaitable async iterator.

Fetches videos that belong to the user. If you have specific video ids use fetch_videos()

Changed in version 3.0.

Parameters
  • period (str) – The period for which to fetch videos. Valid values are all, day, week, month. Defaults to all

  • sort (str) – Sort orders of the videos. Valid values are time, trending, views, Defaults to time

  • type (Optional[str]) – Type of the videos to fetch. Valid values are upload, archive, highlight, all. Defaults to all

  • use_app_token (bool) – Whether to use an app access token, or use a user OAuth token. Defaults to False.

Return type

Video]

get_predictions(prediction_id: str | None = None) HTTPAwaitableAsyncIterator[Prediction]#

This function returns an awaitable async iterator.

Gets information on a prediction or the list of predictions if no id is provided. Requires an OAuth token with the channel:read:predictions or channel:manage:predictions scope.

Changed in version 3.0.

Parameters

prediction_id (str | None) – ID of the prediction to receive information about.

Return type

AwaitableAsyncIterator`[:class:`Prediction]

coroutine modify_channel(game_id: int | None = None, language: str | None = None, title: str | None = None, content_classification_labels: list[dict[str, str | bool]] | None = None, is_branded_content: bool | None = None) None#

This function is a coroutine.

Modify stream information. Requires an OAuth token with the channel:manage:broadcast scope.

Changed in version 3.0.

Parameters
  • game_id (int) – Optional game ID being played on the channel. Use 0 to unset the game.

  • language (str) – Optional language of the channel. A language value must be either the ISO 639-1 two-letter code for a supported stream language or “other”.

  • title (str) – Optional title of the stream.

  • content_classification_labels (list[dict[str, Union[str, bool]]]) –

    List of labels that should be set as the Channel’s CCLs.

    Note

    Example of a content classification labels

    ccl = [{"id": "Gambling", "is_enabled": False}, {"id": "DrugsIntoxication", "is_enabled": False}]
    await my_partial_user.modify_stream(content_classification_labels=ccl)
    

  • is_branded_content (bool) – Boolean flag indicating if the channel has branded content.

coroutine shoutout(target_broadcaster: BaseUser, moderator: twitchio.models.BaseUser | None = None) None#

This function is a coroutine. Sends a Shoutout to the specified broadcaster. Rate Limits: The broadcaster may send a Shoutout once every 2 minutes. They may send the same broadcaster a Shoutout once every 60 minutes. Requires an OAuth token with the moderator:manage:shoutouts scope.

Changed in version 3.0.

Parameters
  • target_broadcaster (BaseUser) – The ID of the broadcaster that is recieving the shoutout.

  • moderator (BaseUser) – The ID of the broadcaster or a user that is one of the broadcaster’s moderators. Setting this will attempt to fetch the request using the moderators token, otherwise the broadcasters will be used.

coroutine start_commercial(length: Literal[30, 60, 90, 120, 150, 180]) dict#

This function is a coroutine.

Starts a commercial on the channel. Requires an OAuth token with the channel:edit:commercial scope.

Parameters

length (int) – the length of the commercial. Should be one of 30, 60, 90, 120, 150, 180

Return type

dict a dictionary with length, message, and retry_after

coroutine update_chat_settings(moderator: twitchio.models.BaseUser | None = None, emote_mode: bool | None = None, follower_mode: bool | None = None, follower_mode_duration: int | None = None, slow_mode: bool | None = None, slow_mode_wait_time: int | None = None, subscriber_mode: bool | None = None, unique_chat_mode: bool | None = None, non_moderator_chat_delay: bool | None = None, non_moderator_chat_delay_duration: int | None = None)#

This function is a coroutine.

Updates the current chat settings for this channel/broadcaster.

Changed in version 3.0.

Parameters
  • moderator (BaseUser | None) – A moderator to update the chat settings as. Setting this will attempt to fetch the request using the moderators token, otherwise the broadcasters will be used.

  • token (str) – An oauth token with the moderator:manage:chat_settings scope.

  • emote_mode (Optional[bool]) – A boolean to determine whether chat must contain only emotes or not.

  • follower_mode (Optional[bool]) – A boolean to determine whether chat must contain only emotes or not.

  • follower_mode_duration (Optional[int]) – The length of time, in minutes, that the followers must have followed the broadcaster to participate in chat. Values: 0 (no restriction) through 129600 (3 months). The default is 0.

  • slow_mode (Optional[bool]) – A boolean to determine whether the broadcaster limits how often users in the chat room are allowed to send messages.

  • slow_mode_wait_time (Optional[int]) – The amount of time, in seconds, that users need to wait between sending messages. Values: 3 through 120 (2 minute delay). The default is 30 seconds.

  • subscriber_mode (Optional[bool]) – A boolean to determine whether only users that subscribe to the broadcaster’s channel can talk in chat.

  • unique_chat_mode (Optional[bool]) – A boolean to determine whether the broadcaster requires users to post only unique messages in chat.

  • non_moderator_chat_delay (Optional[bool]) – A boolean to determine whether the broadcaster adds a short delay before chat messages appear in chat.

  • non_moderator_chat_delay_duration (Optional[int]) – The amount of time, in seconds, that messages are delayed from appearing in chat. Valid values: 2, 4 and 6.

Return type

twitchio.ChatSettings

coroutine update_extensions(extensions: ExtensionBuilder) ActiveExtensionType#

This function is a coroutine.

Updates a users extensions. See the ExtensionBuilder for information on how to use it. Requires an OAuth token with the user:edit:broadcast scope.

Parameters

extensions (twitchio.ExtensionBuilder) – A twitchio.ExtensionBuilder to be given to the twitch api

Return type

dict[str, dict[int, twitchio.ActiveExtension]]

property channel: twitchio.channel.Channel | None#

Returns the Channel associated with this user. Could be None if you are not part of the channel’s chat.

Return type

Channel | None

class twitchio.Client(token_handler: ~twitchio.tokens.BaseTokenHandler, heartbeat: float | None = 30.0, verified: bool | None = False, join_timeout: float | None = 15.0, initial_channels: list[str] | tuple[str] | collections.abc.Callable[[], list[str]] | collections.abc.Coroutine[Any, Any, None] | None = None, shard_manager: ~typing.Type[~twitchio.shards.BaseShardManager] = <class 'twitchio.shards.DefaultShardManager'>, cache_size: int | None = None, **kwargs)#

THe main Twitch HTTP and IRC Client.

This client can be used as a standalone to both HTTP and IRC or used together.

Parameters
  • token_handler (BaseTokenHandler) – Your token handler instance. See token handling

  • heartbeat (float | None) – An optional heartbeat to provide to keep connections over proxies and such alive. Defaults to 30.0.

  • verified (bool | None) – Whether or not your bot is verified or not. Defaults to False.

  • join_timeout (float | None) – An optional float to use to timeout channel joins. Defaults to 15.0.

  • initial_channels (list[str] | tuple[str] | callable | coroutine | None) – An optional list or tuple of channels to join on bot start. This may be a callable or coroutine, but must return a list or tuple.

  • shard_limit (int) – The amount of channels per websocket. Defaults to 100 channels per socket.

  • cache_size (int | None) – The size of the internal channel cache. Defaults to unlimited.

add_event_listener(event_name: str, callback: Callable[[Any], Coroutine[Any, Any, None]]) Event#

Adds an event listener to the Client. The event name must not have whitespace, and must not start with event_.

Changed in version 3.0: This is now publicly documented.

Parameters
  • event_name (str) – The event to dispatch this listener for.

  • callback (Coroutine) – An async function that takes one argument. It will be called whenever the event is dispatched.

Returns

Not much use anywhere except removing events, which typically won’t need to be done manually.

Return type

Event

coroutine delete_videos(target: BaseUser, ids: list[int | twitchio.models.Video]) list[int]#

This function is a coroutine.

Delete videos from the api. Returns the video ids that were successfully deleted.

Requires an OAuth token with the channel:manage:videos scope.

Changed in version 3.0: Removed the token parameter. Added the ``target` parameter.

Parameters
  • target (BaseUser) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

  • ids (list[int]) – A list of video ids from the channel of the oauth token to delete.

Return type

list[int]

dispatch_listeners(event_name: str, arg: Any) None#

Dispatches listeners for the specified event. The event name cannot have whitespace or start with event_.

Changed in version 3.0: Events now only take 1 parameter.

Parameters
  • event_name (str) – The event to dispatch.

  • arg (Any) – The argument to pass to the listeners.

coroutine event_join(channel: Channel, chatter: PartialChatter) None#

This function is a coroutine.

Event fired when a JOIN is received via Twitch.

Parameters
  • channel (Channel) –

  • chatter (PartialChatter) –

coroutine event_message(message: Message) None#

This function is a coroutine.

Event fired when receiving a message in a joined channel.

Parameters

message (Message) – The message received via Twitch.

Return type

None

coroutine event_part(channel: twitchio.channel.Channel | None, chatter: PartialChatter) None#

This function is a coroutine.

Event fired when a PART is received via Twitch.

Parameters
  • channel (Optional[Channel]) – … Could be None if the channel is not in your cache.

  • chatter (PartialChatter) –

coroutine event_raw_data(data: str) None#

This function is a coroutine.

Event fired with the raw data received, unparsed, by Twitch.

Parameters

data (str) – The data received from Twitch.

Return type

None

coroutine event_raw_payload(payload: IRCPayload) None#

This function is a coroutine.

Event fired with the parsed IRC payload object.

Parameters

payload (IRCPayload) – The parsed IRC payload from Twitch.

Return type

None

coroutine event_ready() None#

This function is a coroutine.

Event fired when the bot has completed startup. This includes all shards being ready.

Return type

None

coroutine event_shard_ready(number: int) None#

This function is a coroutine.

Event fired when a shard becomes ready.

Parameters

number (int) – The shard number identifier.

Return type

None

coroutine fetch_channel_info(broadcaster_ids: list[int], target: twitchio.models.BaseUser | None = None) list[twitchio.models.ChannelInfo]#

This function is a coroutine.

Retrieve channel information from the API.

Parameters
  • broadcaster_ids (list[str]) – A list of channel IDs to request from API. Returns empty list if no channel was found. You may specify a maximum of 100 IDs.

  • target (Optional[BaseUser]) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

list[twitchio.ChannelInfo]

coroutine fetch_chatter_colors(user_ids: list[int], target: twitchio.models.BaseUser | None = None) list[twitchio.models.ChatterColor]#

This function is a coroutine.

Fetches the color of a chatter.

Changed in version 3.0: Removed the token parameter. Added the target parameter.

Parameters
  • user_ids (list[int]) – List of user ids to fetch the colors for.

  • target (Optional[BaseUser]) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

list[twitchio.ChatterColor]

coroutine fetch_cheermotes(user_id: int | None = None, target: twitchio.models.BaseUser | None = None) list[twitchio.models.CheerEmote]#

This function is a coroutine.

Fetches cheermotes from the twitch API.

Parameters
  • user_id (Optional[int]) – The channel id to fetch from.

  • target (Optional[BaseUser]) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

list[twitchio.CheerEmote]

fetch_clips(ids: list[str], game_id: str | None = None, target: twitchio.models.BaseUser | None = None) HTTPAwaitableAsyncIterator[Clip]#

This function returns an awaitable async iterator.

Fetches clips by clip id or game id. To fetch clips by user id, use twitchio.PartialUser.fetch_clips().

Changed in version 3.0: Now returns an AAI

Parameters
  • ids (list[str]) – A list of clip ids.

  • game_id (str) – A game id.

  • target (Optional[BaseUser]) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

Clip]

coroutine fetch_content_classification_labels(locale: str | None = None)#

This function is a coroutine.

Fetches information about Twitch content classification labels.

Parameters

locale (Optional[str]) – Locale for the Content Classification Labels.

Return type

List[twitchio.ContentClassificationLabel]

fetch_games(ids: list[int] | None = None, names: list[str] | None = None, igdb_ids: list[int] | None = None, target: twitchio.models.BaseUser | None = None) HTTPAwaitableAsyncIterator[Game]#

This function returns an awaitable async iterator.

Fetches games by id, name or IGDB id. At least one id or name must be provided.

Changed in version 3.0: Now returns an AAI

Parameters
  • ids (list[int] | None) – An optional list of game ids.

  • names (list[str] | None) – An optional list of game names.

  • igdb_ids (list[int] | None) – An optional list of IGDB ids.

  • target (BaseUser | None) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

Game]

coroutine fetch_global_chat_badges(target: twitchio.models.BaseUser | None = None) list[twitchio.models.ChatBadge]#

This function is a coroutine.

Fetches Twitch’s list of chat badges, which users may use in any channel’s chat room.

Parameters

target (BaseUser | None) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

list[ChatBadges]

fetch_streams(user_ids: list[int] | None = None, game_ids: list[int] | None = None, user_logins: list[str] | None = None, languages: list[str] | None = None, type: Literal['all', 'live'] = 'all', target: twitchio.models.BaseUser | None = None) HTTPAwaitableAsyncIterator[Stream]#

This function returns an awaitable async iterator.

Fetches live streams from the helix API.

Changed in version 3.0: Now returns an AAI.

Parameters
  • user_ids (Optional[list[int]]) – user ids of people whose streams to fetch

  • game_ids (Optional[list[int]]) – game ids of streams to fetch

  • user_logins (Optional[list[str]]) – user login names of people whose streams to fetch

  • languages (Optional[list[str]]) – language for the stream(s). ISO 639-1 or two letter code for supported stream language

  • type (Literal["all", "live"]) – The type of stream to fetch. Defaults to “all”.

  • target (BaseUser | None) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

Stream]

fetch_tags(ids: list[str] | None = None, target: twitchio.models.BaseUser | None = None) HTTPAwaitableAsyncIterator[Tag]#

This function returns an awaitable async iterator.

Fetches stream tags.

Changed in version 3.0: Now returns an AAI. Added the target parameter.

Parameters
  • ids (list[str] | None) – The ids of the tags to fetch.

  • target (BaseUser | None) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

Tag]

coroutine fetch_team(team_name: str | None = None, team_id: int | None = None, target: twitchio.models.BaseUser | None = None) Team#

This function is a coroutine.

Fetches information for a specific Twitch Team. You must provide one of name or id.

Changed in version 3.0: Added the target parameter.

Parameters
  • name (str | None) – Team name to fetch.

  • id (int | None) – Team id to fetch.

  • target (BaseUser | None) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

twitchio.Team

fetch_top_games(target: twitchio.models.BaseUser | None = None) HTTPAwaitableAsyncIterator[Game]#

This function returns an awaitable async iterator.

Fetches the top streamed games from the api.

Changed in version 3.0: Now returns an AAI. Added the target parameter.

Parameters

target (BaseUser | None) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

Game]

coroutine fetch_user(name: str | None = None, id: int | None = None, target: twitchio.models.BaseUser | None = None) twitchio.models.User | None#

This function is a coroutine.

Fetches a user from twitch. This is the same as fetch_users(), but only returns one User, instead of a list. You may only provide either name or id, not both.

Changed in version 3.0: Now returns User | None instead of raising IndexError when the user isn’t found.

Parameters
  • name (Optional[str]) – A username.

  • id (Optional[int]) – A user ID.

  • target (Optional[BaseUser]) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

User

fetch_users(names: list[str] | None = None, ids: list[int] | None = None, target: twitchio.models.BaseUser | None = None) HTTPAwaitableAsyncIterator[User]#

This function returns an awaitable async iterator.

Fetches users from twitch. You can provide any combination of up to 100 names and ids, but you must pass at least 1.

Changed in version 3.0: Now returns an AAI

Parameters
  • names (Optional[list[str]]) – A list of usernames.

  • ids (Optional[list[Union[str, int]]) – A list of IDs.

  • target (Optional[BaseUser]) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

User]

fetch_videos(ids: list[int] | None = None, game_id: int | None = None, period: Literal['all', 'day', 'week', 'month'] = 'all', sort: Literal['time', 'trending', 'views'] = 'time', type: Literal['all', 'upload', 'archive', 'highlight'] = 'all', language: str | None = None, target: twitchio.models.BaseUser | None = None) HTTPAwaitableAsyncIterator[Video]#

This function returns an awaitable async iterator.

Fetches videos by id or game id. To fetch videos by user id, use twitchio.PartialUser.fetch_videos().

Changed in version 3.0: Parameters now use Literal instead of str | None where applicable. Now returns an AAI.

Parameters
  • ids (Optional[list[int]]) – A list of video ids up to 100.

  • game_id (Optional[int]) – A game to fetch videos from. Limit 1.

  • period (Optional[str]) – The period for which to fetch videos. Valid values are all, day, week, month. Defaults to all. Cannot be used when video id(s) are passed.

  • sort (Optional[str]) – Sort orders of the videos. Valid values are time, trending, views, Defaults to time. Cannot be used when video id(s) are passed.

  • type (Optional[str]) – Type of the videos to fetch. Valid values are all, upload, archive, highlight. Defaults to all. Cannot be used when video id(s) are passed.

  • language (Optional[str]) – Language of the videos to fetch. Must be an ISO-639-1 two letter code. Cannot be used when video id(s) are passed.

  • target (Optional[BaseUser]) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

Video]

get_channel(name: str, /) twitchio.channel.Channel | None#

Method which returns a channel from cache if it exits.

Could be None if the channel is not in cache.

Parameters

name (str) – The name of the channel to search cache for.

Return type

Channel | None

get_message(id_: str, /) twitchio.message.Message | None#

Method which returns a message from cache if it exists.

Could be None if the message is not in cache.

Parameters

id (str) – The message ID to search cache for.

Return type

Message | None

get_partial_user(user_id: int | str, user_name: str | None) PartialUser#

Creates a PartialUser with the provided user_id and user_name.

Parameters
  • user_id (int | str) – The numeric ID of the user.

  • user_name (str) – The name of the user.

Return type

PartialUser

listener(name_or_function: Callable[[Any], Coroutine[Any, Any, None]]) Event#
listener(name_or_function: str) Callable[[Callable[[Any], Coroutine[Any, Any, None]]], Event]

A decorator for adding event listeners to the Client. This can be used in two different ways.

@client.listener
async def event_message(message: twitchio.Message) -> None:
    ...

Or, 2)

@client.listener("message") # or "event_message"
async def this_is_a_message_listener(message: twitchio.Message) -> None:
    ...

Changed in version 3.0: This can now be used without the name in the decorator.

Returns

Turns the function into an Event. The function can still be called like normal, but has some special properties for dispatching events to it.

Return type

Event

remove_event_listener(listener: twitchio.client.Event | collections.abc.Callable) None#

Removes an event listener from the Client. You must pass an Event or a function that has been marked as an event (usually with the @client.listener decorator.)

Changed in version 3.0: This is now publicly documented.

Parameters

listener (Event | Coroutine) – The listener to remove, or its corresponding Event container.

run() None#

A blocking call that starts and connects the bot to IRC.

This methods abstracts away starting and cleaning up for you.

Warning

You should not use this method unless you are connecting to IRC.

Note

Since this method is blocking it should be the last thing to be called. Anything under it will only execute after this method has completed.

Note

If you want to take more control over cleanup, see close().

search_categories(query: str, target: twitchio.models.BaseUser | None = None) HTTPAwaitableAsyncIterator[Game]#

This function returns an awaitable async iterator.

Searches Twitch categories.

Changed in version 3.0: Now returns an AAI

Parameters
  • query (str) – The query to search for.

  • target (Optional[BaseUser]) – The target of this HTTP call. Passing a user will tell the library to put this call under the authorized token for that user, if one exists in your token handler.

Return type

Game]

search_channels(query: str, *, live_only=False, target: twitchio.models.BaseUser | None = None) HTTPAwaitableAsyncIterator[SearchUser]#

This function is a coroutine.

Searches channels for the given query.

Changed in version 3.0: Now returns an AAI

Parameters
  • query (str) – The query to search for.

  • live_only (bool) – Only search live channels. Defaults to False.

Return type

SearchUser]

coroutine setup() None#

This function is a coroutine.

Method called before the Client has logged in to Twitch, used for asynchronous setup.

Useful for setting up state, like databases, before the client has logged in.

New in version 3.0.

coroutine start() None#

This function is a coroutine.

This method connects to twitch’s IRC servers, and prepares to handle incoming messages. This method will not return until all the IRC shards have been closed

coroutine update_chatter_color(target: BaseUser, color: Union[Literal['blue', 'blue_violet', 'cadet_blue', 'chocolate', 'coral', 'dodger_blue', 'firebrick', 'golden_rod', 'green', 'hot_pink', 'orange_red', 'red', 'sea_green', 'spring_green', 'yellow_green'], str]) None#

This function is a coroutine.

Updates the color of the specified user in the specified channel/broadcaster’s chat.

Requires an OAuth token with the user:manage:chat_color scope.

Changed in version 3.0: Removed token & user_id parameters. Added literals to color parameter.

Parameters
  • target (BaseUser) – The user to change the chat color for.

  • color (str) –

    All users may use any of the named colors: - blue - blue_violet - cadet_blue - chocolate - coral - dodger_blue - firebrick - golden_rod - green - hot_pink - orange_red - red - sea_green - spring_green - yellow_green

    Turbo and Prime users may specify a named color or a Hex color code like #9146FF.

Raises

BadRequest – The color parameter was either not valid, or you provided a hex value without being a prime or turbo member.

property nick: str | None#

The bots nickname.

This may be None if a shard has not become ready, or you have entered invalid credentials.

property nickname: str | None#

The bots nickname.

This may be None if a shard has not become ready, or you have entered invalid credentials.

class twitchio.BaseTokenHandler#

A base class to manage user tokens.

This class is designed to be subclassed. The library will aggressively cache user tokens, and will only call your code when a token cannot be found in the cache.

A short example of a subclassed token handler:

import os
import json
import twitchio

class MyTokenHandler(twitchio.BaseTokenHandler):
    def __init__(self):
        # While we recommend storing tokens in an actual database, this will suffice for the example.
        # A JSON file will suffice fine for a personal bot, however if you wish to expand to support more users,
        # using a JSON file is an extremely bad idea.

        # This example JSON file stores tokens in a dict of user_id: [token, refresh_token]. It does not take scopes into account,
        # which you should probably do.

        with open("tokens.json") as file:
            self.user_tokens = json.load(file)

        super().__init__()

    def get_client_credentials(self): # can be async
        return os.getenv("CLIENT_ID"), os.getenv("CLIENT_SECRET")

    def get_irc_token(self): # can be async
        return twitchio.Token(os.getenv("IRC_TOKEN"))

    async def get_user_token(self, user: twitchio.BaseUser, scopes: tuple[str]): # can be sync
        user_id = user.id
        if user_id not in self.user_tokens:
            raise RuntimeError("User not found :(")

        tokens = self.user_tokens[user_id]
        return twitchio.Token(tokens[0], refresh_token=tokens[1])
coroutine event_token_expired(token: Token) twitchio.tokens.Token | None#

This function is a coroutine. Method to be overriden in a subclass.

This function is a special event hook into the HTTP system. It is called when a token expires and cannot be refreshed automatically. From here, you may return a new token for the HTTP system to use instead. Alternatively, you may return None to signal the HTTP system to call get_user_token() instead.

Note

This typically means that user interaction is required to acquire a new token. An exception to this is if you have not provided a client_secret in get_client_credentials(), then the library will not attempt to refresh tokens.

Parameters

token (Token) – The token that expired and could not be refreshed.

Return type

Token | None

coroutine event_token_refreshed(old: Token, new: Token) None#

This function could be a coroutine. Method to be overriden in a subclass.

This function is called whenever the library refreshes a user token. You do not need to do anything from this event, however this can be used to perform actions with the token. For example, this can be used to update tokens in a database, or inform a user.

When this is called, the token has already been refeshed

Parameters
  • old (Token) – The token before it was refreshed.

  • new (Token) – The token after it was refreshed.

coroutine get_client_credentials() tuple[str, str | None]#

This function could be a coroutine. Method to be overriden in a subclass.

This should return a tuple of (client id, client secret). The client secret is not required, however the client id is required to make requests to the twitch API. The client secret is required to automatically refresh user tokens when they expire, however it is not required to access the twitch API.

coroutine get_client_token() BaseToken#

This function could be a coroutine. Method to be overriden in a subclass.

This should return a client token (generated with client id and client secret). If not implemented, the library will attempt to generate one with the credentials returned from get_client_credentials().

Warning

If the library is unable to fetch any client token, it will hard crash. If you do not have means to generate a client token, you may not be able to use certain methods. You will also need to ensure any Client methods have a target parameter specified, as client tokens are used when no target user is specified.

Returns

The client token.

Return type

BaseToken

coroutine get_irc_token(user_name: str | None) Token#

This function could be a coroutine. Method to be overriden in a subclass.

This should return a Token containing an OAuth token with the chat:login scope.

Parameters

user_name (str | None) – The name of the user to return a chat token for. Typically, this will be None when using the default shard manager. For a more in-depth explanation, see the shard manager documentation.

Returns

The token with which to connect

Return type

Token

coroutine get_user_token(user: BaseUser | PartialUser, scopes: tuple[str]) Token#

This function could be a coroutine. Method to be overriden in a subclass.

This function receives a user and a list of scopes that the request needs any one of to make the request. It should return a Token object.

Note

It is a good idea to pass a refresh token if you have one available, the library will automatically handle refreshing tokens if one is provided.

Parameters
  • user (BaseUser | BaseUser) – The user that a token is expected for.

  • scopes (tuple[str]) – A list of scopes that the endpoint needs one of. Any one or more of the scopes must be present on the returned token to successfully make the request

Returns

The token for the associated user.

Return type

Token