miggor-StreamGraph/addons/no_twitch/eventsub_socket.gd
Eroax b94c3702cc Updates NoTwitch + Implements Twitch Get Request (#124)
Patch the Array/Dictionary/Array problem with NoTwitch
Plus tweaks the existing Connected Account Info + Chat Received Nodes.
Reviewed-on: https://codeberg.org/StreamGraph/StreamGraph/pulls/124
Co-authored-by: Eroax <eroaxebusiness@duck.com>
Co-committed-by: Eroax <eroaxebusiness@duck.com>
2024-03-17 10:28:54 +00:00

116 lines
2.3 KiB
GDScript

extends Websocket_Client
const eventsub_url := "wss://eventsub.wss.twitch.tv/ws"
## Stores the "session id" for this EventSub connection.
var session_id
var connection : No_Twitch
signal notif_received(data)
signal welcome_received()
var keepalive_timer := 0
var timeout_time : int
## Dictionary used for storing all the subscribed events in the format "subscription_type : No_Twitch.EventSub_Subscription"
var subscribed_events : Dictionary
func _init(owner, timeout : int):
connection = owner
timeout_time = timeout
packet_received.connect(data_received)
## Overrides the default poll function for [Websocket_Client] to add functionality for a keepalive timer and reconnecting when the connection is lost.
func poll_socket():
super()
keepalive_timer += connection.get_process_delta_time()
if keepalive_timer >= timeout_time:
socket_closed.emit()
close()
connect_to_eventsub(subscribed_events.values())
## Handles setting up the connection to EventSub with an Array of the Events that should be subscribed to.
func connect_to_eventsub(events : Array[No_Twitch.EventSub_Subscription]):
connect_to_url(eventsub_url)
await welcome_received
for all in events:
subscribed_events[all.subscription_type] = all
return await subscribe_to_events(events)
## Utility function for subscribing to multiple Twitch EventSub events at once.
func subscribe_to_events(events : Array[No_Twitch.EventSub_Subscription]):
var responses : Array[No_Twitch.HTTPResponse]
for all in events:
responses.append(await connection.add_eventsub_subscription(all))
if responses.size() == 1:
return responses[0]
return responses
func new_eventsub_subscription(info, event_subscription : No_Twitch.EventSub_Subscription):
if !event_subscription in subscribed_events:
subscribed_events[event_subscription.subscription_type] = event_subscription
event_subscription.sub_id = info.data.id
func data_received(packet : PackedByteArray):
var info = JSON.parse_string(packet.get_string_from_utf8())
match info.metadata.message_type:
"session_welcome":
session_id = info.payload.session.id
welcome_received.emit()
"session_ping":
send_pong(info)
"notification":
notif_received.emit(info)
"session_keepalive":
keepalive_timer = 0
print(info)
func send_pong(pong):
pong.metadata.message_type = "session_pong"
send_text(str(pong))