EventSub Websocket#
Note
EventSub Websocket is targeted at programs which have to subscribe to topics for just a single broadcaster.
Should you need to target multiple broadcasters or are building a server side projekt, look at EventSub Webhook
EventSub lets you listen for events that happen on Twitch.
The EventSub client runs in its own thread, calling the given callback function whenever an event happens.
Listening to topics#
After you started your EventSub client, you can use the listen_
prefixed functions to listen to the topics you are interested in.
Look at Available Topics and Callback Payloads to find the topics you are interested in.
The function you hand in as callback will be called whenever that event happens with the event data as a parameter, the type of that parameter is also listed in the link above.
Code Example#
from twitchAPI.helper import first
from twitchAPI.twitch import Twitch
from twitchAPI.oauth import UserAuthenticationStorageHelper
from twitchAPI.object.eventsub import ChannelFollowEvent
from twitchAPI.eventsub.websocket import EventSubWebsocket
from twitchAPI.type import AuthScope
import asyncio
APP_ID = 'your_app_id'
APP_SECRET = 'your_app_secret'
TARGET_SCOPES = [AuthScope.MODERATOR_READ_FOLLOWERS]
async def on_follow(data: ChannelFollowEvent):
# our event happend, lets do things with the data we got!
print(f'{data.event.user_name} now follows {data.event.broadcaster_user_name}!')
async def run():
# create the api instance and get user auth either from storage or website
twitch = await Twitch(APP_ID, APP_SECRET)
helper = UserAuthenticationStorageHelper(twitch, TARGET_SCOPES)
await helper.bind()
# get the currently logged in user
user = await first(twitch.get_users())
# create eventsub websocket instance and start the client.
eventsub = EventSubWebsocket(twitch)
eventsub.start()
# subscribing to the desired eventsub hook for our user
# the given function (in this example on_follow) will be called every time this event is triggered
# the broadcaster is a moderator in their own channel by default so specifying both as the same works in this example
# We have to subscribe to the first topic within 10 seconds of eventsub.start() to not be disconnected.
await eventsub.listen_channel_follow_v2(user.id, user.id, on_follow)
# eventsub will run in its own process
# so lets just wait for user input before shutting it all down again
try:
input('press Enter to shut down...')
except KeyboardInterrupt:
pass
finally:
# stopping both eventsub as well as gracefully closing the connection to the API
await eventsub.stop()
await twitch.close()
asyncio.run(run())
- class twitchAPI.eventsub.websocket.EventSubWebsocket#
Bases:
EventSubBase
- __init__(twitch, connection_url=None, subscription_url=None, callback_loop=None, revocation_handler=None)#
- Parameters:
twitch¶ (
Default:) – The Twitch instance to be usedconnection_url¶ (
Default:) – Alternative connection URL, usefull for development with the twitch-clisubscription_url¶ (
Default:) – Alternative subscription URL, usefull for development with the twitch-clicallback_loop¶ (
Default:) –The asyncio eventloop to be used for callbacks.
Set this if you or a library you use cares about which asyncio event loop is running the callbacks. Defaults to the one used by EventSub Websocket.
revocation_handler¶ (
Default:) – Optional handler for when subscriptions get revoked.Default:None
-
subscription_url: Default:#
The URL where subscriptions are being send to. Defaults to
TWITCH_API_BASE_URL
-
connection_url: Default:#
The URL where the websocket connects to. Defaults to
TWITCH_EVENT_SUB_WEBSOCKET_URL
-
active_session: Default:#
The currently used session
-
revokation_handler: Default:#
Optional handler for when subscriptions get revoked.
-
reconnect_delay_steps: Default:#
Time in seconds between reconnect attempts
- start()#
Starts the EventSub client
- Raises:
RuntimeError – If EventSub is already running
UnauthorizedException – If Twitch instance is missing user authentication
- async stop()#
Stops the EventSub client
- Raises:
RuntimeError – If EventSub is not running
- async listen_channel_ad_break_begin(broadcaster_user_id, callback)#
A midroll commercial break has started running.
Requires the
CHANNEL_READ_ADS
scope.- Parameters:
broadcaster_user_id¶ (
Default:) – The ID of the broadcaster that you want to get Channel Ad Break begin notifications for.callback¶ (
Default:) – function for callback- Return type:
Default:- async listen_channel_ban(broadcaster_user_id, callback)#
A viewer is banned from the specified channel.
User Authentication with
CHANNEL_MODERATE
is required.For more information see here: https://dev.twitch.tv/docs/eventsub/eventsub-subscription-types#channelban
- Parameters:
broadcaster_user_id¶ (
Default:) – the id of the user you want to listen tocallback¶ (
Default:) – function for callback- Raises:
EventSubSubscriptionConflict – if a conflict was found with this subscription (e.g. already subscribed to this exact topic)
EventSubSubscriptionTimeout – if
wait_for_subscription_confirm
is true and the subscription was not fully confirmed in timeEventSubSubscriptionError – if the subscription failed (see error message for details)
TwitchBackendException – if the subscription failed due to a twitch backend error
- Return type:
Default:- async listen_channel_charity_campaign_donate(broadcaster_user_id, callback)#
Sends a notification when a user donates to the broadcaster’s charity campaign.
Requires the
CHANNEL_READ_CHARITY
auth scope.For more information see here: https://dev.twitch.tv/docs/eventsub/eventsub-subscription-types/#channelcharity_campaigndonate
- Parameters:
broadcaster_user_id¶ (
Default:) – The ID of the broadcaster that you want to receive notifications about when users donate to their campaign.callback¶ (
Default:) – function for callback- Raises:
EventSubSubscriptionConflict – if a conflict was found with this subscription (e.g. already subscribed to this exact topic)
EventSubSubscriptionTimeout – if
wait_for_subscription_confirm
is true and the subscription was not fully confirmed in timeEventSubSubscriptionError – if the subscription failed (see error message for details)
TwitchBackendException – if the subscription failed due to a twitch backend error
- Return type:
Default:- async listen_channel_charity_campaign_progress(broadcaster_user_id, callback)#
Sends notifications when progress is made towards the campaign’s goal or when the broadcaster changes the fundraising goal.
Requires the
CHANNEL_READ_CHARITY
auth scope.For more information see here: https://dev.twitch.tv/docs/eventsub/eventsub-subscription-types/#channelcharity_campaignprogress
- Parameters:
broadcaster_user_id¶ (
Default:) – The ID of the broadcaster that you want to receive notifications about when their campaign makes progress or is updated.callback¶ (
Default:) – function for callback- Raises:
EventSubSubscriptionConflict – if a conflict was found with this subscription (e.g. already subscribed to this exact topic)
EventSubSubscriptionTimeout – if
wait_for_subscription_confirm
is true and the subscription was not fully confirmed in timeEventSubSubscriptionError – if the subscription failed (see error message for details)
TwitchBackendException – if the subscription failed due to a twitch backend error
- Return type:
Default:- async listen_channel_charity_campaign_start(broadcaster_user_id, callback)#
Sends a notification when the broadcaster starts a charity campaign.
Requires the
CHANNEL_READ_CHARITY
auth scope.For more information see here: https://dev.twitch.tv/docs/eventsub/eventsub-subscription-types/#channelcharity_campaignstart
- Parameters:
broadcaster_user_id¶ (
Default:) – The ID of the broadcaster that you want to receive notifications about when they start a charity campaign.callback¶ (
Default:) – function for callback- Raises:
EventSubSubscriptionConflict – if a conflict was found with this subscription (e.g. already subscribed to this exact topic)
EventSubSubscriptionTimeout – if
wait_for_subscription_confirm
is true and the subscription was not fully confirmed in timeEventSubSubscriptionError – if the subscription failed (see error message for details)
TwitchBackendException – if the subscription failed due to a twitch backend error
- Return type:
Default:- async listen_channel_charity_campaign_stop(broadcaster_user_id, callback)#
Sends a notification when the broadcaster stops a charity campaign.
Requires the
CHANNEL_READ_CHARITY
auth scope.For more information see here: https://dev.twitch.tv/docs/eventsub/eventsub-subscription-types/#channelcharity_campaignstop
- Parameters:
broadcaster_user_id¶ (
Default:) – The ID of the broadcaster that you want to receive notifications about when they stop a charity campaign.callback¶ (
Default:) – function for callback- Raises:
EventSubSubscriptionConflict – if a conflict was found with this subscription (e.g. already subscribed to this exact topic)
EventSubSubscriptionTimeout – if
wait_for_subscription_confirm
is true and the subscription was not fully confirmed in timeEventSubSubscriptionError – if the subscription failed (see error message for details)
TwitchBackendException – if the subscription failed due to a twitch backend error
- Return type:
Default:- async listen_channel_chat_clear(broadcaster_user_id, user_id, callback)#
A moderator or bot has cleared all messages from the chat room.
Requires
USER_READ_CHAT
scope from chatting user. If app access token used, then additionally requiresUSER_BOT
scope from chatting user, and eitherCHANNEL_BOT
scope from broadcaster or moderator status.For more information see here: https://dev.twitch.tv/docs/eventsub/eventsub-subscription-types/#channelchatclear
- Parameters:
broadcaster_user_id¶ (
Default:) – User ID of the channel to receive chat clear events for.user_id¶ (
Default:) – The user ID to read chat as.callback¶ (
Default:) – function for callback- Return type:
Default:- async listen_channel_chat_clear_user_messages(broadcaster_user_id, user_id, callback)#
A moderator or bot has cleared all messages from a specific user.
Requires
USER_READ_CHAT
scope from chatting user. If app access token used, then additionally requiresUSER_BOT
scope from chatting user, and eitherCHANNEL_BOT
scope from broadcaster or moderator status.- Parameters:
broadcaster_user_id¶ (
Default:) – User ID of the channel to receive chat clear user messages events for.user_id¶ (
Default:) – The user ID to read chat as.callback¶ (
Default:) – function for callback- Return type:
Default:- async listen_channel_chat_message(broadcaster_user_id, user_id, callback)#
Any user sends a message to a specific chat room.
- Parameters:
broadcaster_user_id¶ (
Default:) – User ID of the channel to receive chat message events for.user_id¶ (
Default:) – The user ID to read chat as.callback¶ (
Default:) – function for callback- Return type:
Default:- async listen_channel_chat_message_delete(broadcaster_user_id, user_id, callback)#
A moderator has removed a specific message.
Requires
USER_READ_CHAT
scope from chatting user. If app access token used, then additionally requiresUSER_BOT
scope from chatting user, and eitherCHANNEL_BOT
scope from broadcaster or moderator status.- Parameters:
broadcaster_user_id¶ (
Default:) – User ID of the channel to receive chat message delete events for.user_id¶ (
Default:) – The user ID to read chat as.callback¶ (
Default:) – function for callback- Return type:
Default:- async listen_channel_chat_notification(broadcaster_user_id, user_id, callback)#
A notification for when an event that appears in chat has occurred.
Requires
USER_READ_CHAT
scope from chatting user. If app access token used, then additionally requiresUSER_BOT
scope from chatting user, and eitherCHANNEL_BOT
scope from broadcaster or moderator status.