Twitch chat bot¶
TwitchChat lets a daemon hear a Twitch channel and answer in it. It is an
adapter only: it converts chat messages into ChatEvents and sends text. Who
the bot is, when it speaks and what it may say belong to the consumer.
from hypeman_social.social import CHAT_REGISTRY
chat = CHAT_REGISTRY['twitch']()
if chat.is_available():
chat.start(lambda event: print(event.author_id, event.text))
chat.send('your_channel', 'hello chat')
Why the bot is not the broadcaster's account¶
A chat bot holds a token that can type in chat. If that token is the
broadcaster's, a leak lets an attacker speak as the broadcaster, with the
broadcaster's moderation powers, on the channel that matters most. A separate
account limits the damage to one muted, removable, replaceable user. It also
lets is_self tell the bot's own messages from the broadcaster's, and Twitch's
documented Chat Bot Badge requires that the bot account is not the channel's
broadcaster.
Set the bot account up¶
- Create a new Twitch account for the bot with its own email address. Do not reuse the broadcaster's email.
- Turn on two-factor authentication for that account.
- Log in as the bot and register an application in the Twitch developer
console. Choose a confidential client type, set an OAuth redirect URL you
control (for a one-time token run,
http://localhost:3000is enough), and note the Client ID and generate a client secret. - Request the minimum scopes, authorising as the bot account through the
authorization code flow (
https://id.twitch.tv/oauth2/authorize, then the code exchange athttps://id.twitch.tv/oauth2/token): user:read:chatto receive chat messagesuser:write:chatto send chat messages
Do not request more. user:bot and channel:bot are only needed for the
app-access-token path and the Chat Bot Badge, which this adapter does not use.
5. Find the bot's numeric user id (the user_id in the validate response, or
the Get Users endpoint).
6. Put the values in Doppler (the only secret store this adapter is designed
around; see Configuration). Never put them in code, a
committed file or a chat log.
How the broadcaster lets the bot in¶
With a user access token, the bot reads and writes chat as itself. A bot that is not a moderator is subject to Twitch's ordinary chat rules for the channel (follower-only, slow mode, and so on), and the broadcaster can make the bot a moderator or VIP to lift them. Twitch returns 403 when the bot is banned or timed out. The broadcaster does not hand over any token.
Token handling¶
- At start, on a schedule of 55 minutes (Twitch requires hourly) and whenever
the expiry Twitch reported is within 15 minutes, the token is checked against
https://id.twitch.tv/oauth2/validate. The adapter keeps the absolute expiry deadline from that answer (anchored at the moment the request was sent) and never treats the token as usable past it, even while validation is failing for transient reasons. Anexpires_inof zero or less means expired: refresh now, and refuse the token if that fails. A missing or malformedexpires_inmeans the lifetime is unknown: the hourly validation and the 401 refresh path still apply. It also checks that the token belongs to the configured application and tobot_user_idand that it carries both scopes. - A 401, or a token close to expiry, triggers a refresh with the refresh token. A replacement access token is staged and only handed to senders after it has passed validation; a replacement that fails validation (for example a token for another user) is never used to send.
- If the refresh fails, the adapter becomes unavailable and logs one error. It
tries once more every 15 minutes. That retry invalidates the cached secrets
(
reset_secret_cache(), a re-fetch of the Doppler project) and re-reads them, so correcting the values in Doppler heals it without a restart. Missing configuration (an empty access token, say) takes the same cooldown-guarded path. The next-attempt deadline is advanced before every recovery attempt, whatever its outcome, so a failing recovery is never retried in a loop. - Refresh tokens. Twitch documents that a refresh token may change when it is used, and that the application should store the replacement. The adapter always keeps the newest pair in memory and uses it for the next refresh. On recovery it adopts the stored pair only if the stored values differ from the ones it read last time (the operator replaced them); an unchanged, older stored pair never overwrites a newer one held in memory.
- Persisting a replacement. Writing back to Doppler would need a Doppler
token with write access, which this adapter deliberately does not ask for and
has no code path for. Pass
on_token_refresh=callback(access_token, refresh_token)toTwitchChat(...)if the consumer wants to persist the new pair somewhere secure. The latest pair is delivered at least once; intermediate pairs may be skipped (one slot, latest wins, drained by one dispatcher thread), so an older pair is never delivered after a newer one, memory stays bounded, and a slow callback never holds the adapter's lock or stalls receiving and sending. Anything the callback raises, includingBaseException, is contained: only the exception class name is logged, never its text, and the dispatcher keeps running (and is restarted if it ever dies). The adapter never logs the values.stop()lets the pending pair finish and joins the thread. - What a restart does. Without a callback the replacement lives in memory only, so a restart reads the stored pair again. Whether the old refresh token still works after Twitch has issued a replacement is not something I could confirm in the documentation, so after a long uptime, or after a log line saying the tokens were refreshed, treat an unavailable bot at startup as a reason to regenerate the stored tokens (see Revoke and rotate).
- Nothing logs a token, a client secret or an
Authorizationheader, and exception messages are logged by type only. Text taken from a response is never logged verbatim: revocation statuses anddrop_reason.codevalues are checked against a short allowlist and anything else logs a fixed marker. Sanitised internal exceptions are raised outside theexceptblock so they carry no__context__with the original text. Tests enforce this.
Receiving: what is accepted¶
- Only
channel.chat.messagenotifications for the configured channel. No other subscription is made. - Shared chat. In a shared chat session Twitch delivers other participants'
messages to this channel with
source_broadcaster_user_idset to the channel they came from. These are dropped (not delivered withbridged=Falseand the origin discarded). The choice is deliberate: the bot's conversation is the configured channel's. (Whether a send is allowed is decided separately, by asking Twitch at send time; see Limits.) - Replay and duplicates. Notifications whose
message_timestampis missing or older than ten minutes (Twitch's own guidance for replay protection), or more than 60 seconds in the future, are dropped; timestamp offsets must be well formed (hours 0 to 23, minutes 0 to 59). Everymessage_idis remembered for the whole window plus the skew (11 minutes), by time, with a hard cap of 100,000 ids; at the cap the oldest id is dropped and one warning says the replay guarantee is weaker. Delivery from Twitch is at-least-once, so consumers should still be idempotent byChatEvent.message_id. If the host clock is more than a minute off, messages look old or future and are dropped; one warning says so. Retention uses a monotonic clock while freshness uses wall time, so a wall-clock rollback larger than the 60 s skew can let an old frame through; consumers must be idempotent bymessage_id. - Frame size. A frame, or a fragmented message in total, over 1 MiB of
encoded bytes is refused as soon as its header declares the length (a
websocket-clientsubclass checks the length before the payload is read, and the connection is dropped and re-established). Residual: an accepted 1 MiB frame is buffered in memory, roughly two to four times that transiently while it is joined and decoded. The bounded reader leans onwebsocket-clientinternals, so the package is pinned to the tested range>=1.6.0,<2(the tests run on 1.9.0 and 1.9.2). There is no fallback to the stock reader: before the first connection a probe feeds an in-process socket pair a header declaring an oversize frame and checks it is refused before the payload is read. If the hook is missing or the probe fails,is_available()returnsFalsewith one error naming the installed version, and nothing connects. - Connections. Handshake redirects are not followed. A reconnect URL must be
wss://eventsub.wss.twitch.tv, port absent or 443, no user information, path empty or/ws(the forms the EventSub documentation shows).
Limits the adapter applies¶
- Messages are collapsed to one line and cut at 500 characters (the documented Send Chat Message limit). Control characters (NUL, ESC and the rest of C0/C1) are removed and all whitespace collapses to single spaces.
- A message that begins with
/or.(Twitch chat commands such as/ban,/me,.timeout) is refused:send()returnsFalseand the log says why, never the text. ConstructTwitchChat(allow_command_prefix=True)to allow them. - A local limiter allows 15 messages per 30 seconds and one every 1.5 seconds.
Twitch allows 20 per 30 seconds and one per second per channel for a sender
that is not the broadcaster, a moderator or a VIP, and ignores a bot that
exceeds them for an hour. When the limiter says no,
send()returnsFalseat once; it never waits. A 429 response pauses sending for up to a minute. - The bot only sends to the channel it was configured for.
- Shared chat on send: asked every time, refused unless clear. With a user
access token, Twitch delivers an outgoing message to every channel in a
shared chat session, and the local channel allowlist cannot prevent that
(
for_source_onlyexists only for app access tokens, which this adapter does not use). So everysend()calls Get Shared Chat Session (user token) immediately before the POST, under the same lock as the POST, and returnsFalseif a session is active or the answer is unknown (error, timeout, a 401 that one refresh did not fix, unparseable). Nothing is cached, there is no timer and no subscription; the check is repeated before the retry POST that follows a 401. A session that starts between the check and the POST can still receive one message: the API offers no way to close that race, and sending with an app access token andfor_source_onlyis the only way to close it (not implemented). stop()returns nothing (theChatReceivercontract). Readstopped_cleanlyafterwards: it isFalse(and a warning is logged) if the receiver or the token persistence thread is still alive after five seconds, for example blocked in a connect. The worker is kept,start()refuses to run a second receiver until it exits, and it abandons the connection by itself when the connect returns.
Revoke and rotate¶
If a token or secret may have leaked, or the bot is misbehaving:
- Stop the daemon (or call
stop()). - As the bot account, disconnect the application at
https://www.twitch.tv/settings/connections. This invalidates its tokens. - In the developer console, generate a new client secret for the application (this invalidates the old one). If the Client ID itself was exposed, register a new application.
- Run the authorization code flow again as the bot to get a new access token and refresh token.
- Update
client_secret,access_tokenandrefresh_tokenin Doppler, and rotate anything else that sat beside them. - Start the daemon.
is_available()re-reads the secrets and validates before the bot speaks again.
To remove the bot entirely, ban or remove the account in the channel and delete the application.
What was and was not verified¶
Read from dev.twitch.tv while writing this: the EventSub WebSocket handshake
(welcome, keepalive, reconnect, revocation, close codes), the reconnect URL form
(wss://eventsub.wss.twitch.tv?...), the ten-minute replay guidance and
message_id de-duplication on the EventSub overview, the
channel.chat.message event fields, reply.parent_message_id and the
source_broadcaster_user_id shared-chat fields, Send Chat Message (endpoint,
body, 500 character limit, is_sent and drop_reason, status codes, and the
shared-chat behaviour per token type), token validation and its hourly
requirement, token refresh (including that refresh tokens may change), the scope
names, and the chat rate limits.
Also read: Get Shared Chat Session (user or app token; an empty data array
means not sharing).
Not verified: the full set of drop_reason.code values (Twitch does not list
them, so only automod_held is echoed); the exact badge set_id strings (broadcaster, moderator,
subscriber, vip are used; the pages I read gave only bits and subscriber
as examples); whether the 500 limit counts code points or UTF-16 units;
Twitch's duplicate-message rules; whether Twitch treats other leading
characters than / and . as commands; and the behaviour of an old refresh
token after a replacement is issued. Nothing here was run against live Twitch.