From f91c9f9554b94df2eef4a0b018d677775759df60 Mon Sep 17 00:00:00 2001 From: 5elenay <5elenay@protonmail.com> Date: Fri, 20 Aug 2021 21:53:16 +0300 Subject: [PATCH] added simple event handler. --- client.go | 8 ++++++++ websocket.go | 22 +++++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/client.go b/client.go index 94e72fe..2bade28 100644 --- a/client.go +++ b/client.go @@ -13,4 +13,12 @@ const ( type Client struct { Token string Socket gowebsocket.Socket + + // Functions + OnReadyFunction func() +} + +// On Ready event will run when websocket connection is started and bot is ready to work. +func (c *Client) OnReady(fn func()) { + c.OnReadyFunction = fn } diff --git a/websocket.go b/websocket.go index 0e98a9b..51bec7f 100644 --- a/websocket.go +++ b/websocket.go @@ -1,12 +1,18 @@ package revoltgo import ( + "encoding/json" "fmt" "time" "github.com/sacOO7/gowebsocket" ) +// Dummy struct for parse gateway events. +type GatewayType struct { + Type string `json:"type"` +} + func (c *Client) Start() { // Create new socket c.Socket = gowebsocket.New(WS_URL) @@ -17,10 +23,24 @@ func (c *Client) Start() { } c.Socket.OnTextMessage = func(message string, _ gowebsocket.Socket) { - if message == "{\"type\":\"Authenticated\"}" { + // Parse data + rawData := &GatewayType{} + err := json.Unmarshal([]byte(message), rawData) + + if err != nil { + c.Destroy() + panic(err) + } + + if rawData.Type == "Authenticated" { go c.ping() } + // Check events + if rawData.Type == "Ready" { + c.OnReadyFunction() + } + fmt.Println(message) }