mirror of
https://codeberg.org/SafeTwitch/safetwitch-backend.git
synced 2024-12-22 13:13:00 -05:00
Autoconnect websocket
This commit is contained in:
parent
6b1895b958
commit
127aca6e3b
1 changed files with 26 additions and 3 deletions
|
@ -4,8 +4,10 @@ import (
|
|||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"safetwitch-backend/extractor/chat/structs"
|
||||
|
||||
|
@ -13,13 +15,16 @@ import (
|
|||
)
|
||||
|
||||
var u = url.URL{Scheme: "wss", Host: "irc-ws.chat.twitch.tv:443", Path: "/"}
|
||||
var conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)
|
||||
var conn *websocket.Conn
|
||||
var _ *http.Response
|
||||
var err error
|
||||
|
||||
// If the connection is ready to subscribe to channels
|
||||
var connectionReady = false
|
||||
var streamersFollowing = map[string]bool{}
|
||||
|
||||
func BeginTwitchChatConnection() {
|
||||
conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)
|
||||
log.Println("Connecting to Twitch IRC")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
|
@ -46,13 +51,31 @@ func BeginTwitchChatConnection() {
|
|||
if err != nil {
|
||||
log.Printf("Failed to read message: %v", err)
|
||||
connectionReady = false
|
||||
BeginTwitchChatConnection()
|
||||
expReconnect()
|
||||
break
|
||||
}
|
||||
|
||||
parseMessage(string(msg))
|
||||
RemoveUnusedStreamers()
|
||||
//fmt.Println("Received message from server:", string(msg))
|
||||
}
|
||||
}
|
||||
|
||||
func expReconnect() {
|
||||
// Attempt to reconnect with exponential backoff
|
||||
waitTime := time.Second
|
||||
maxWaitTime := 30 * time.Second
|
||||
|
||||
for {
|
||||
log.Printf("Attempting to reconnect in %v...\n", waitTime)
|
||||
time.Sleep(waitTime)
|
||||
|
||||
BeginTwitchChatConnection()
|
||||
|
||||
if waitTime < maxWaitTime {
|
||||
waitTime *= 2
|
||||
} else {
|
||||
waitTime = maxWaitTime
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue