-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
opensea.go
107 lines (91 loc) · 2.1 KB
/
opensea.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package seadisc
import (
"encoding/json"
"log"
"os"
"os/signal"
"strings"
"time"
"github.com/gorilla/websocket"
)
var (
BaseUrl string = "wss://{network}stream.openseabeta.com/socket/websocket?token="
)
type Sea struct {
SocketUrl string
}
func (s *Sea) SetSocketUrl(network, token string) {
var net string = ""
if strings.ToLower(network) != "main" {
net = "testnets-"
}
s.SocketUrl = strings.Replace(BaseUrl, "{network}", net, 1)
}
func (s *Sea) OpenseaSocket() {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
// Connect to websocket
c, _, err := websocket.DefaultDialer.Dial(s.SocketUrl, nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
// log.Printf("recv: %s", message)
Discord(message)
}
}()
ticker := time.NewTicker(time.Second * 30)
defer ticker.Stop()
// Heartbit
heartbitSchema := map[string]interface{}{
"topic": "phoenix",
"event": "heartbeat",
"payload": map[string]interface{}{},
"ref": 0,
}
heartbit, _ := json.Marshal(heartbitSchema)
// Subscribe to all event
eventSchema := map[string]interface{}{
"topic": "collection:*",
"event": "phx_join",
"payload": map[string]interface{}{},
"ref": 0,
}
event, _ := json.Marshal(eventSchema)
_ = c.WriteMessage(websocket.TextMessage, event)
for {
select {
case <-done:
return
case <-ticker.C:
err := c.WriteMessage(websocket.TextMessage, heartbit)
if err != nil {
log.Println("write:", err)
return
}
case <-interrupt:
log.Println("interrupt")
// Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection.
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
select {
case <-done:
case <-time.After(time.Second):
}
return
}
}
}