TwitchGod/http/websocket_client.gd
2024-09-28 18:34:09 -04:00

71 lines
1.4 KiB
GDScript

extends Node
class_name WebsocketClient
signal opened
signal received(type: TwitchEvents.Event, data: Dictionary)
const URL = "wss://eventsub.wss.twitch.tv/ws"
var socket := WebSocketPeer.new()
var connection_state := WebSocketPeer.STATE_CLOSED
var id := ""
# -- Built in Methods
func _process(delta: float) -> void:
socket.poll()
var new_connection_state := socket.get_ready_state()
if new_connection_state != connection_state: _change_state(new_connection_state)
match connection_state:
WebSocketPeer.STATE_OPEN:
_read_data()
# -- Public Methods
## Open up the websocket to start listening
func open():
socket.connect_to_url(URL)
# -- Private Methods
func _change_state(new_state: WebSocketPeer.State):
match new_state:
WebSocketPeer.STATE_OPEN:
opened.emit()
connection_state = new_state
func _read_data():
while (socket.get_available_packet_count()):
var packet := socket.get_packet()
var data = _read_packet(packet)
var payload = data.payload
match data.metadata.message_type:
"session_welcome":
id = payload.session.id
"session_keepalive":
pass
"session_reconnect":
pass
_:
var event_type = TwitchEvents.get_event_type_from_name(payload.subscription.type)
received.emit(event_type, payload.event)
func _read_packet(packet: PackedByteArray):
var string = ""
for chunk in packet:
string += char(chunk)
var data = JSON.parse_string(string)
return data