Skip to content

API Reference

This section is generated directly from package docstrings.

Client

EventClient

EventClient(
    events_url: str,
    *,
    config: ClientConfig | None = None,
    rate_limiter: AsyncLimiter | None = None,
    session: ClientSession | None = None,
)

Async long-poll client for Events API streams.

Handles URL parsing, retries, rate limiting, and nextUrl continuation. Use as an async context manager and async iterator.

Initialize a client from an Events API URL.

Parameters:

Name Type Description Default
events_url str

Full Events API URL provided by upstream.

required
config ClientConfig | None

Optional client configuration overrides.

None
rate_limiter AsyncLimiter | None

Optional shared limiter for multiple clients.

None
session ClientSession | None

Optional caller-owned aiohttp session. Caller-owned sessions are not closed by EventClient.

None
Attributes
base_url property
base_url: str

Canonical Events API base URL.

username property
username: str

Account username parsed from the Events API URL.

config property
config: ClientConfig

Immutable client configuration.

session property
session: ClientSession | None

Active HTTP session, or None before entry and after close.

Methods:
poll async
poll() -> list[Event]

Fetch one batch of events from the API.

Makes one request and updates _next_url for the next poll.

Returns:

Type Description
list[Event]

List of events received, or an empty list on timeout.

Raises:

Type Description
EventsError

If shutdown has started.

CancelledError

If close() cancels this poll.

close async
close() -> None

Close the HTTP session and reset poll state.

Safe to call multiple times. Called automatically by context exit. Internally created sessions are closed; caller-owned injected sessions remain open. After close(), the instance cannot be reopened.

Raises:

Type Description
CancelledError

If the caller of close() is cancelled while waiting for in-flight polls to finish shutting down.

Router

Router

Router()

Dispatch events to registered async handlers.

Wildcard handlers run before type-specific handlers. Exceptions raised by handlers are logged and do not stop dispatch of remaining handlers.

Initialize an empty handler registry.

Methods:
on
on(event_type: EventType) -> Callable[[HandlerFunc], HandlerFunc]

Register a handler for one event type.

Parameters:

Name Type Description Default
event_type EventType

Event category to associate with the handler.

required

Returns:

Type Description
Callable[[HandlerFunc], HandlerFunc]

Decorator that registers the handler and returns it unchanged.

on_any
on_any(func: None = None) -> Callable[[HandlerFunc], HandlerFunc]
on_any(func: HandlerFunc) -> HandlerFunc
on_any(func: HandlerFunc | None = None) -> Callable[[HandlerFunc], HandlerFunc] | HandlerFunc

Register a handler for all event types.

Supports both @router.on_any and @router.on_any().

Parameters:

Name Type Description Default
func HandlerFunc | None

Optional handler when used as @router.on_any.

None

Returns:

Type Description
Callable[[HandlerFunc], HandlerFunc] | HandlerFunc

Registered handler when func is provided, otherwise a decorator.

dispatch async
dispatch(event: Event) -> None

Dispatch an event to matching handlers.

Executes wildcard handlers first, then type-specific handlers, in registration order. Handler exceptions are caught, logged, and do not propagate or prevent other handlers from executing.

Parameters:

Name Type Description Default
event Event

Event instance to dispatch to registered handlers.

required
Note

Handlers run sequentially. A slow handler will delay all subsequent ones for that event.

HandlerFunc module-attribute

HandlerFunc: TypeAlias = Callable[[Event], Awaitable[None]]

Async handler signature accepted by Router decorators.

Configuration

ClientConfig

Bases: BaseModel

Immutable settings for EventClient.

Controls long-poll timeout, retry backoff, and strict validation mode.

Attributes
timeout class-attribute instance-attribute
timeout: int = Field(default=10, gt=0)

Server long-poll timeout in seconds.

strict_validation class-attribute instance-attribute
strict_validation: bool = False

Raise on invalid events vs. skip and log.

retry_attempts class-attribute instance-attribute
retry_attempts: int = Field(default=10, ge=1)

Total attempts including the initial request (must be >= 1).

retry_backoff class-attribute instance-attribute
retry_backoff: float = Field(default=1.0, ge=0)

Initial retry delay in seconds.

retry_factor class-attribute instance-attribute
retry_factor: float = Field(default=2.0, gt=0)

Backoff multiplier applied after each retry.

retry_max_delay class-attribute instance-attribute
retry_max_delay: float = Field(default=300.0, ge=0)

Maximum delay between retries in seconds.

auth_retry_attempts class-attribute instance-attribute
auth_retry_attempts: int = Field(default=1, ge=1)

Total auth-status attempts before returning the final 401/403.

auth_retry_delay class-attribute instance-attribute
auth_retry_delay: float = Field(default=0.0, ge=0)

Fixed delay in seconds between auth-status retry attempts.

auth_retry_status_codes class-attribute instance-attribute
auth_retry_status_codes: frozenset[int] = AUTH_ERROR_STATUS_CODES

HTTP status codes eligible for auth-status retry behavior.

Events

Event

Bases: BaseEventModel

Top-level event container.

Typed convenience accessors cache validated nested payload fields when the event is created and return None for missing or invalid values.

Warning

String fields in payload data are untrusted user input.

Attributes
type class-attribute instance-attribute
type: EventType = Field(alias='method')

Type of the event.

raw_method class-attribute instance-attribute
raw_method: str | None = None

Original API method name when it is not recognized by this client.

id instance-attribute
id: str

Unique identifier for the event.

data class-attribute instance-attribute
data: Mapping[str, object] = Field(default_factory=dict, alias='object')

Immutable event data payload.

user property
user: User | None

User data if present and valid.

message property
message: Message | None

Message data if present and valid.

broadcaster property
broadcaster: str | None

Broadcaster username, or None if missing or invalid.

tip property
tip: Tip | None

Tip data if present and valid (TIP events only).

media property
media: Media | None

Media purchase data if present and valid (MEDIA_PURCHASE only).

room_subject property
room_subject: RoomSubject | None

Room subject if present and valid (ROOM_SUBJECT_CHANGE only).

Methods:
model_post_init
model_post_init(context: object) -> None

Cache the validated sub-models using one payload registry.

EventType

Bases: StrEnum

Event type values emitted by the API.

Attributes
BROADCAST_START class-attribute instance-attribute
BROADCAST_START = 'broadcastStart'

Broadcaster has started streaming.

BROADCAST_STOP class-attribute instance-attribute
BROADCAST_STOP = 'broadcastStop'

Broadcaster has stopped streaming.

ROOM_SUBJECT_CHANGE class-attribute instance-attribute
ROOM_SUBJECT_CHANGE = 'roomSubjectChange'

Room subject or title has changed.

USER_ENTER class-attribute instance-attribute
USER_ENTER = 'userEnter'

User has entered the room.

USER_LEAVE class-attribute instance-attribute
USER_LEAVE = 'userLeave'

User has left the room.

FOLLOW class-attribute instance-attribute
FOLLOW = 'follow'

User has followed the broadcaster.

UNFOLLOW class-attribute instance-attribute
UNFOLLOW = 'unfollow'

User has unfollowed the broadcaster.

FANCLUB_JOIN class-attribute instance-attribute
FANCLUB_JOIN = 'fanclubJoin'

User has joined the fan club.

CHAT_MESSAGE class-attribute instance-attribute
CHAT_MESSAGE = 'chatMessage'

Chat message has been sent.

PRIVATE_MESSAGE class-attribute instance-attribute
PRIVATE_MESSAGE = 'privateMessage'

Private message has been sent.

TIP class-attribute instance-attribute
TIP = 'tip'

User has sent a tip.

MEDIA_PURCHASE class-attribute instance-attribute
MEDIA_PURCHASE = 'mediaPurchase'

User has purchased media.

UNKNOWN class-attribute instance-attribute
UNKNOWN = 'unknown'

Event type is unrecognized by this client version.

Media

Bases: BaseEventModel

Payload for mediaPurchase events.

Attributes
id instance-attribute
id: str

Identifier of the purchased media.

name instance-attribute
name: str

Name of the purchased media.

type instance-attribute
type: str

Type of the purchased media.

Possible values: "photos", "video".

tokens instance-attribute
tokens: int

Number of tokens spent on the media purchase.

Message

Bases: BaseEventModel

Payload for chatMessage and privateMessage events.

Attributes
message instance-attribute
message: str

Content of the message.

bg_color class-attribute instance-attribute
bg_color: str | None = None

Background color of the message.

color class-attribute instance-attribute
color: str | None = None

Text color of the message.

font class-attribute instance-attribute
font: str | None = None

Font style of the message.

orig class-attribute instance-attribute
orig: str | None = None

Original message content.

from_user class-attribute instance-attribute
from_user: str | None = None

Username of the sender.

to_user class-attribute instance-attribute
to_user: str | None = None

Username of the recipient.

is_private property
is_private: bool

True if this is a private message.

RoomSubject

Bases: BaseEventModel

Payload for roomSubjectChange events.

Attributes
subject instance-attribute
subject: str

The room subject or title.

Tip

Bases: BaseEventModel

Payload for tip events.

Attributes
tokens instance-attribute
tokens: int

Number of tokens tipped.

is_anon class-attribute instance-attribute
is_anon: bool = False

Whether the tip is anonymous.

message class-attribute instance-attribute
message: str | None = None

Optional message attached to the tip.

User

Bases: BaseEventModel

User metadata attached to an event.

Attributes
username instance-attribute
username: str

Display name of the user.

color_group class-attribute instance-attribute
color_group: str | None = None

User name-color group.

Known values: "o" (owner), "m" (moderator), "f" (fanclub), "l" (dark purple), "p" (light purple), "tr" (dark blue), "t" (light blue), "g" (grey).

fc_auto_renew class-attribute instance-attribute
fc_auto_renew: bool = False

Whether the user's fanclub membership is a recurring subscription.

gender class-attribute instance-attribute
gender: str | None = None

User gender code.

Known values: "m" (male), "f" (female), "c" (couple), "t" (trans).

has_darkmode class-attribute instance-attribute
has_darkmode: bool = False

Whether the user has dark mode enabled.

has_tokens class-attribute instance-attribute
has_tokens: bool = False

Whether the user has at least 1 token.

in_fanclub class-attribute instance-attribute
in_fanclub: bool = False

Whether the user is in the fan club.

in_private_show class-attribute instance-attribute
in_private_show: bool = False

Whether the user is in the broadcaster's private show.

is_broadcasting class-attribute instance-attribute
is_broadcasting: bool = False

Whether the user is currently broadcasting.

is_follower class-attribute instance-attribute
is_follower: bool = False

Whether the user is a follower.

is_mod class-attribute instance-attribute
is_mod: bool = False

Whether the user is a moderator.

is_owner class-attribute instance-attribute
is_owner: bool = False

Whether the user is the room owner.

is_silenced class-attribute instance-attribute
is_silenced: bool = False

Whether the user is silenced.

is_spying class-attribute instance-attribute
is_spying: bool = False

Whether the user is spying on a private show.

language class-attribute instance-attribute
language: str | None = None

User's preferred language.

Known values: "de" (German), "en" (English), "es" (Spanish), "fr" (French), "it" (Italian), "ja" (Japanese), "ko" (Korean), "pl" (Polish), "pt" (Portuguese), "ru" (Russian), "zh" (Chinese).

recent_tips class-attribute instance-attribute
recent_tips: str | None = None

Recent tipping activity bucket.

Possible values: "none", "few", "some", "lots", "tons".

Note

The string value "none" is truthy. Compare explicitly with recent_tips is None versus recent_tips == "none".

subgender class-attribute instance-attribute
subgender: str | None = None

Subgender code when gender is "t".

Possible values: "tf", "tm", "tn". None when not provided.

Exceptions

EventsError

EventsError(message: str, *, status_code: int | None = None, response_text: str | None = None)

Bases: Exception

Base exception for client and API failures.

Carries optional HTTP status and response text details when available.

Initialize error with message and optional HTTP details.

Parameters:

Name Type Description Default
message str

Human-readable description of the failure.

required
status_code int | None

Optional HTTP status code returned by the API.

None
response_text str | None

Optional raw response body. Truncated to 200 characters to reduce PII exposure in structured exception loggers and error-reporting tools.

None
Attributes
status_code instance-attribute
status_code: int | None = status_code

HTTP status code if available.

response_text instance-attribute
response_text: str | None = (
    truncate_text(response_text) if response_text is not None else response_text
)

Raw response body, truncated to 200 characters to limit PII in logs.

AuthError

AuthError(message: str, *, status_code: int | None = None, response_text: str | None = None)

Bases: EventsError

Authentication failure.

Raised when the API rejects configured credentials.

EventsUrlError

EventsUrlError(message: str, *, status_code: int | None = None, response_text: str | None = None)

Bases: EventsError

The Events API URL is malformed or unsupported.

ClientRequestError

ClientRequestError(
    message: str, *, status_code: int | None = None, response_text: str | None = None
)

Bases: HttpStatusError

HTTP 4xx failure excluding auth and rate limiting.

HttpStatusError

HttpStatusError(message: str, *, status_code: int | None = None, response_text: str | None = None)

Bases: EventsError

Base error for HTTP status failures other than auth checks.

RateLimitError

RateLimitError(message: str, *, status_code: int | None = None, response_text: str | None = None)

Bases: HttpStatusError

HTTP 429 failure after retry attempts are exhausted.

ServerError

ServerError(message: str, *, status_code: int | None = None, response_text: str | None = None)

Bases: HttpStatusError

HTTP 5xx or equivalent upstream server failure.

StrictValidationError

StrictValidationError(
    message: str, *, status_code: int | None = None, response_text: str | None = None
)

Bases: EventsError

Event validation failed while strict mode was enabled.